Merge branch 'main' into tsBuildImpliedNodeFormat

This commit is contained in:
Sheetal Nandi
2022-10-31 10:24:28 -07:00
2130 changed files with 67141 additions and 50812 deletions
+2 -14
View File
@@ -17,20 +17,8 @@ build.json
*.config
scripts/debug.bat
scripts/run.bat
scripts/word2md.js
scripts/buildProtocol.js
scripts/ior.js
scripts/configurePrerelease.js
scripts/open-user-pr.js
scripts/open-cherry-pick-pr.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js
scripts/produceLKG.js
scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.js
scripts/generateLocalizedDiagnosticMessages.js
scripts/configureLanguageServiceBuild.js
scripts/*.js.map
scripts/typings/
scripts/**/*.js
scripts/**/*.js.map
coverage/
internal/
**/.DS_Store
+2 -1
View File
@@ -4,7 +4,8 @@
/lib/**
/src/lib/*.generated.d.ts
# Ignore all compiled script outputs
/scripts/*.js
/scripts/**/*.js
/scripts/**/*.d.*
# But, not the ones that are hand-written.
# TODO: remove once scripts are pure JS
!/scripts/browserIntegrationTest.js
+1 -1
View File
@@ -2,7 +2,7 @@ const fs = require("fs");
const path = require("path");
const rulesDir = path.join(__dirname, "scripts", "eslint", "rules");
const ext = ".js";
const ext = ".cjs";
const ruleFiles = fs.readdirSync(rulesDir).filter((p) => p.endsWith(ext));
module.exports = {
+27 -12
View File
@@ -12,17 +12,6 @@
"plugins": [
"@typescript-eslint", "jsdoc", "no-null", "import", "eslint-plugin-local"
],
"overrides": [
// By default, the ESLint CLI only looks at .js files. But, it will also look at
// any files which are referenced in an override config. Most users of typescript-eslint
// get this behavior by default by extending a recommended typescript-eslint config, which
// just so happens to override some core ESLint rules. We don't extend from any config, so
// explicitly reference TS files here so the CLI picks them up.
//
// ESLint in VS Code will lint any opened file (so long as it's not eslintignore'd), so
// that will work regardless of the below.
{ "files": ["*.ts", "*.mts", "*.cts", "*.mjs", "*.cjs"] }
],
"rules": {
"@typescript-eslint/adjacent-overload-signatures": "error",
"@typescript-eslint/array-type": "error",
@@ -151,5 +140,31 @@
"no-prototype-builtins": "error",
"no-self-assign": "error",
"no-dupe-else-if": "error"
}
},
"overrides": [
// By default, the ESLint CLI only looks at .js files. But, it will also look at
// any files which are referenced in an override config. Most users of typescript-eslint
// get this behavior by default by extending a recommended typescript-eslint config, which
// just so happens to override some core ESLint rules. We don't extend from any config, so
// explicitly reference TS files here so the CLI picks them up.
//
// ESLint in VS Code will lint any opened file (so long as it's not eslintignore'd), so
// that will work regardless of the below.
//
// The same applies to mjs files; ESLint appears to not scan those either.
{ "files": ["*.ts", "*.mts", "*.cts", "*.mjs", "*.cjs"] },
{
"files": ["*.mjs", "*.mts"],
"rules": {
// These globals don't exist outside of CJS files.
"no-restricted-globals": ["error",
{ "name": "__filename" },
{ "name": "__dirname" },
{ "name": "require" },
{ "name": "module" },
{ "name": "exports" }
]
}
}
]
}
+5 -1
View File
@@ -1,4 +1,8 @@
name : CodeQL Configuration
paths:
- './src'
- src
- scripts
- Gulpfile.mjs
paths-ignore:
- src/lib
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- name: Configure Git, Run Tests, Update Baselines, Apply Fixes
+17
View File
@@ -67,3 +67,20 @@ jobs:
- name: Validate the browser can import TypeScript
run: gulp test-browser-integration
misc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: "*"
check-latest: true
- run: npm ci
- name: Build scripts
run: gulp scripts
- name: ESLint tests
run: gulp run-eslint-rules-tests
+46 -32
View File
@@ -1,50 +1,64 @@
name: "Code scanning - action"
name: "Code Scanning - Action"
on:
push:
branches:
- main
- release-*
pull_request:
branches:
- main
- release-*
schedule:
- cron: '0 19 * * 0'
# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of the month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
# │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ │
# * * * * *
- cron: '30 1 * * 0'
jobs:
CodeQL-Build:
# CodeQL runs on ubuntu-latest and windows-latest
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
runs-on: ubuntu-latest
if: github.repository == 'microsoft/TypeScript'
permissions:
# required for all workflows
security-events: write
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
config-file: ./.github/codeql/codeql-configuration.yml
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
config-file: ./.github/codeql/codeql-configuration.yml
# Override language selection by uncommenting this and choosing your languages
# with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
# ✏️ If the Autobuild fails above, remove it and uncomment the following
# three lines and modify them (or add more) to build your code if your
# project uses a compiled language
#- run: |
# make bootstrap
# make release
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
@@ -22,7 +22,7 @@ jobs:
git config --global user.email "typescriptbot@microsoft.com"
git config --global user.name "TypeScript Bot"
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
repository: 'microsoft/TypeScript-Website'
path: 'ts-site'
@@ -34,7 +34,7 @@ jobs:
git config --unset-all http.https://github.com/.extraheader
git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Website.git
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
repository: 'microsoft/TypeScript-Make-Monaco-Builds'
path: 'monaco-builds'
@@ -0,0 +1,36 @@
name: "typescript-error-deltas Watchdog"
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * 3' # Every Wednesday
jobs:
check-for-recent:
runs-on: ubuntu-latest
if: github.repository == 'microsoft/TypeScript'
permissions:
contents: read # Apparently required to create issues
issues: write
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAGS: "@RyanCavanaugh @DanielRosenwasser @amcasey"
steps:
- name: NewErrors
run: | # --json and --jq prints exactly one issue number per line of output
DATE=$(date --date="7 days ago" --iso-8601)
gh issue list --repo microsoft/typescript --search "[NewErrors] created:>=$DATE" --state all --json number --jq ".[].number" \
| grep -qe "[0-9]" \
|| gh issue create --repo ${{ github.repository }} --title "No NewErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=48)."
- name: ServerErrors TS
run: |
DATE=$(date --date="7 days ago" --iso-8601)
gh issue list --repo microsoft/typescript --search "[ServerErrors][TypeScript] created:>=$DATE" --state all --json number --jq ".[].number" \
| grep -qe "[0-9]" \
|| gh issue create --repo ${{ github.repository }} --title "No TypeScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=59)."
- name: ServerErrors JS
run: |
DATE=$(date --date="7 days ago" --iso-8601)
gh issue list --repo microsoft/typescript --search "[ServerErrors][JavaScript] created:>=$DATE" --state all --json number --jq ".[].number" \
| grep -qe "[0-9]" \
|| gh issue create --repo ${{ github.repository }} --title "No JavaScript ServerErrors issue since $DATE" --body "$TAGS Please check the [pipeline](https://typescript.visualstudio.com/TypeScript/_build?definitionId=58)."
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
steps:
- uses: actions/setup-node@v3
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
fetch-depth: 5
- run: |
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
if: github.repository == 'microsoft/TypeScript'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
# Use NODE_AUTH_TOKEN environment variable to authenticate to this registry.
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- name: npm install and test
run: |
@@ -27,7 +27,7 @@ jobs:
npm pack ./
mv typescript-*.tgz typescript.tgz
- name: Upload built tarfile
uses: actions/upload-artifact@v1
uses: actions/upload-artifact@v3
with:
name: tgz
path: typescript.tgz
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
fetch-depth: 5
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
steps:
- uses: actions/setup-node@v3
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
ref: ${{ github.event.client_payload.branch_name }}
# notably, this is essentially the same script as `new-release-branch.yaml` (with fewer inputs), but it assumes the branch already exists
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
steps:
- uses: actions/setup-node@v3
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.branch_name || github.event.client_payload.branch_name }}
fetch-depth: 0
+1 -1
View File
@@ -9,7 +9,7 @@ jobs:
- name: Get repo name
run: R=${GITHUB_REPOSITORY%?wiki}; echo "BASENAME=${R##*/}" >> $GITHUB_ENV
- name: Checkout ${{ env.BASENAME }}-wiki
uses: actions/checkout@v2
uses: actions/checkout@v3
with:
repository: "${{ GITHUB.repository_owner }}/${{ env.BASENAME }}-wiki"
token: ${{ secrets.TS_BOT_GITHUB_TOKEN }}
+1 -1
View File
@@ -8,7 +8,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- name: Configure Git and Update LKG
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
if: github.repository == 'microsoft/TypeScript'
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
token: ${{ secrets.TS_BOT_GITHUB_TOKEN }}
- uses: actions/setup-node@v3
+2 -16
View File
@@ -40,22 +40,8 @@ tests/cases/**/*.js.map
scripts/eslint/built/
scripts/debug.bat
scripts/run.bat
scripts/word2md.js
scripts/buildProtocol.js
scripts/ior.js
scripts/configurePrerelease.js
scripts/configureLanguageServiceBuild.js
scripts/open-user-pr.js
scripts/open-cherry-pick-pr.js
scripts/processDiagnosticMessages.d.ts
scripts/processDiagnosticMessages.js
scripts/produceLKG.js
scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.js
scripts/generateLocalizedDiagnosticMessages.js
scripts/request-pr-review.js
scripts/errorCheck.js
scripts/*.js.map
scripts/typings/
scripts/**/*.js
scripts/**/*.js.map
coverage/
internal/
**/.DS_Store
+39 -72
View File
@@ -1,20 +1,22 @@
// @ts-check
const path = require("path");
const fs = require("fs");
const log = require("fancy-log");
const newer = require("gulp-newer");
const sourcemaps = require("gulp-sourcemaps");
const del = require("del");
const rename = require("gulp-rename");
const concat = require("gulp-concat");
const merge2 = require("merge2");
const { src, dest, task, parallel, series, watch } = require("gulp");
const { append, transform } = require("gulp-insert");
const { prependFile } = require("./scripts/build/prepend");
const { exec, readJson, needsUpdate, getDiffTool, getDirSize, rm } = require("./scripts/build/utils");
const { runConsoleTests, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests");
const { buildProject, cleanProject, watchProject } = require("./scripts/build/projects");
const cmdLineOptions = require("./scripts/build/options");
import path from "path";
import fs from "fs";
import log from "fancy-log";
import newer from "gulp-newer";
import sourcemaps from "gulp-sourcemaps";
import del from "del";
import rename from "gulp-rename";
import concat from "gulp-concat";
import merge2 from "merge2";
import gulp from "gulp";
import { append, transform } from "gulp-insert";
import { prependFile } from "./scripts/build/prepend.mjs";
import { exec, readJson, needsUpdate, getDiffTool, getDirSize, rm } from "./scripts/build/utils.mjs";
import { runConsoleTests, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } from "./scripts/build/tests.mjs";
import { buildProject, cleanProject, watchProject } from "./scripts/build/projects.mjs";
import cmdLineOptions from "./scripts/build/options.mjs";
const { src, dest, task, parallel, series, watch } = gulp;
const copyright = "CopyrightNotice.txt";
const cleanTasks = [];
@@ -23,9 +25,6 @@ const buildScripts = () => buildProject("scripts");
task("scripts", buildScripts);
task("scripts").description = "Builds files in the 'scripts' folder.";
const cleanScripts = () => cleanProject("scripts");
cleanTasks.push(cleanScripts);
/** @type {{ libs: string[]; paths: Record<string, string | undefined>; }} */
const libraries = readJson("./src/lib/libs.json");
const libs = libraries.libs.map(lib => {
@@ -56,10 +55,10 @@ const diagnosticMessagesJson = "src/compiler/diagnosticMessages.json";
const diagnosticMessagesGeneratedJson = "src/compiler/diagnosticMessages.generated.json";
const generateDiagnostics = async () => {
if (needsUpdate(diagnosticMessagesJson, [diagnosticMessagesGeneratedJson, diagnosticInformationMapTs])) {
await exec(process.execPath, ["scripts/processDiagnosticMessages.js", diagnosticMessagesJson]);
await exec(process.execPath, ["scripts/processDiagnosticMessages.mjs", diagnosticMessagesJson]);
}
};
task("generate-diagnostics", series(buildScripts, generateDiagnostics));
task("generate-diagnostics", generateDiagnostics);
task("generate-diagnostics").description = "Generates a diagnostic file in TypeScript based on an input JSON file";
const cleanDiagnostics = () => del([diagnosticInformationMapTs, diagnosticMessagesGeneratedJson]);
@@ -88,7 +87,7 @@ const localizationTargets = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt
const localize = async () => {
if (needsUpdate(diagnosticMessagesGeneratedJson, generatedLCGFile)) {
return exec(process.execPath, ["scripts/generateLocalizedDiagnosticMessages.js", "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true });
return exec(process.execPath, ["scripts/generateLocalizedDiagnosticMessages.mjs", "src/loc/lcl", "built/local", diagnosticMessagesGeneratedJson], { ignoreExitCode: true });
}
};
@@ -97,7 +96,7 @@ const cleanDebugTools = () => cleanProject("src/debug");
cleanTasks.push(cleanDebugTools);
// Pre-build steps when targeting the LKG compiler
const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildDebugTools));
const lkgPreBuild = parallel(generateLibs, series(generateDiagnostics, buildDebugTools));
const buildTsc = () => buildProject("src/tsc");
task("tsc", series(lkgPreBuild, buildTsc));
@@ -113,7 +112,7 @@ task("watch-tsc", series(lkgPreBuild, parallel(watchLib, watchDiagnostics, watch
task("watch-tsc").description = "Watch for changes and rebuild the command-line compiler only.";
// Pre-build steps when targeting the built/local compiler.
const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildDebugTools, buildTsc));
const localPreBuild = parallel(generateLibs, series(generateDiagnostics, buildDebugTools, buildTsc));
// Pre-build steps to use based on supplied options.
const preBuild = cmdLineOptions.lkg ? lkgPreBuild : localPreBuild;
@@ -335,17 +334,8 @@ task("clean-tests").description = "Cleans the outputs for the test infrastructur
const watchTests = () => watchProject("src/testRunner", cmdLineOptions);
const buildEslintRules = () => buildProject("scripts/eslint");
task("build-eslint-rules", buildEslintRules);
task("build-eslint-rules").description = "Compiles eslint rules to js";
const cleanEslintRules = () => cleanProject("scripts/eslint");
cleanTasks.push(cleanEslintRules);
task("clean-eslint-rules", cleanEslintRules);
task("clean-eslint-rules").description = "Cleans the outputs for the eslint rules";
const runEslintRulesTests = () => runConsoleTests("scripts/eslint/built/tests", "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ false);
task("run-eslint-rules-tests", series(buildEslintRules, runEslintRulesTests));
const runEslintRulesTests = () => runConsoleTests("scripts/eslint/tests", "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ false);
task("run-eslint-rules-tests", runEslintRulesTests);
task("run-eslint-rules-tests").description = "Runs the eslint rule tests";
/** @type { (folder: string) => { (): Promise<any>; displayName?: string } } */
@@ -459,8 +449,8 @@ task("runtests-parallel").flags = {
};
task("test-browser-integration", () => exec(process.execPath, ["scripts/browserIntegrationTest.js"]));
task("test-browser-integration").description = "Runs scripts/browserIntegrationTest.ts which tests that typescript.js loads in a browser";
task("test-browser-integration", () => exec(process.execPath, ["scripts/browserIntegrationTest.mjs"]));
task("test-browser-integration").description = "Runs scripts/browserIntegrationTest.mjs which tests that typescript.js loads in a browser";
task("diff", () => exec(getDiffTool(), [refBaseline, localBaseline], { ignoreExitCode: true, waitForExit: false }));
@@ -486,21 +476,6 @@ task("baseline-accept").description = "Makes the most recent test results the ne
task("baseline-accept-rwc", () => baselineAccept(localRwcBaseline, refRwcBaseline));
task("baseline-accept-rwc").description = "Makes the most recent rwc test results the new baseline, overwriting the old baseline";
const buildLoggedIO = () => buildProject("src/loggedIO/tsconfig-tsc-instrumented.json");
const cleanLoggedIO = () => del("built/local/loggedIO.js");
cleanTasks.push(cleanLoggedIO);
const buildInstrumenter = () => buildProject("src/instrumenter");
const cleanInstrumenter = () => cleanProject("src/instrumenter");
cleanTasks.push(cleanInstrumenter);
const tscInstrumented = () => exec(process.execPath, ["built/local/instrumenter.js", "record", cmdLineOptions.tests || "iocapture", "built/local/tsc.js"]);
task("tsc-instrumented", series(lkgPreBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl, buildLoggedIO, buildInstrumenter), tscInstrumented));
task("tsc-instrumented").description = "Builds an instrumented tsc.js";
task("tsc-instrumented").flags = {
"-t --tests=<testname>": "The test to run."
};
// TODO(rbuckton): Determine if we still need this task. Depending on a relative
// path here seems like a bad idea.
const updateSublime = () => src(["built/local/tsserver.js", "built/local/tsserver.js.map"])
@@ -508,13 +483,9 @@ const updateSublime = () => src(["built/local/tsserver.js", "built/local/tsserve
task("update-sublime", updateSublime);
task("update-sublime").description = "Updates the sublime plugin's tsserver";
const buildImportDefinitelyTypedTests = () => buildProject("scripts/importDefinitelyTypedTests");
const cleanImportDefinitelyTypedTests = () => cleanProject("scripts/importDefinitelyTypedTests");
cleanTasks.push(cleanImportDefinitelyTypedTests);
// TODO(rbuckton): Should the path to DefinitelyTyped be configurable via an environment variable?
const importDefinitelyTypedTests = () => exec(process.execPath, ["scripts/importDefinitelyTypedTests/importDefinitelyTypedTests.js", "./", "../DefinitelyTyped"]);
task("importDefinitelyTypedTests", series(buildImportDefinitelyTypedTests, importDefinitelyTypedTests));
const importDefinitelyTypedTests = () => exec(process.execPath, ["scripts/importDefinitelyTypedTests.mjs", "./", "../DefinitelyTyped"]);
task("importDefinitelyTypedTests", importDefinitelyTypedTests);
task("importDefinitelyTypedTests").description = "Runs the importDefinitelyTypedTests script to copy DT's tests to the TS-internal RWC tests";
const buildReleaseTsc = () => buildProject("src/tsc/tsconfig.release.json");
@@ -544,7 +515,7 @@ const produceLKG = async () => {
throw new Error("Cannot replace the LKG unless all built targets are present in directory 'built/local/'. The following files are missing:\n" + missingFiles.join("\n"));
}
const sizeBefore = getDirSize("lib");
await exec(process.execPath, ["scripts/produceLKG.js"]);
await exec(process.execPath, ["scripts/produceLKG.mjs"]);
const sizeAfter = getDirSize("lib");
if (sizeAfter > (sizeBefore * 1.10)) {
throw new Error("The lib folder increased by 10% or more. This likely indicates a bug.");
@@ -558,28 +529,24 @@ task("LKG").flags = {
};
task("lkg", series("LKG"));
const generateSpec = () => exec("cscript", ["//nologo", "scripts/word2md.js", path.resolve("doc/TypeScript Language Specification - ARCHIVED.docx"), path.resolve("doc/spec-ARCHIVED.md")]);
task("generate-spec", series(buildScripts, generateSpec));
const generateSpec = () => exec("cscript", ["//nologo", "scripts/word2md.mjs", path.resolve("doc/TypeScript Language Specification - ARCHIVED.docx"), path.resolve("doc/spec-ARCHIVED.md")]);
task("generate-spec", generateSpec);
task("generate-spec").description = "Generates a Markdown version of the Language Specification";
task("clean", series(parallel(cleanTasks), cleanBuilt));
task("clean").description = "Cleans build outputs";
const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.js", "dev", "package.json", "src/compiler/corePublic.ts"]);
const configureNightly = () => exec(process.execPath, ["scripts/configurePrerelease.mjs", "dev", "package.json", "src/compiler/corePublic.ts"]);
task("configure-nightly", series(buildScripts, configureNightly));
task("configure-nightly").description = "Runs scripts/configurePrerelease.ts to prepare a build for nightly publishing";
const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/corePublic.ts"]);
task("configure-insiders", series(buildScripts, configureInsiders));
task("configure-insiders").description = "Runs scripts/configurePrerelease.ts to prepare a build for insiders publishing";
const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.mjs", "insiders", "package.json", "src/compiler/corePublic.ts"]);
task("configure-insiders", configureInsiders);
task("configure-insiders").description = "Runs scripts/configurePrerelease.mjs to prepare a build for insiders publishing";
const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.js", "experimental", "package.json", "src/compiler/corePublic.ts"]);
task("configure-experimental", series(buildScripts, configureExperimental));
task("configure-experimental").description = "Runs scripts/configurePrerelease.ts to prepare a build for experimental publishing";
const createLanguageServicesBuild = () => exec(process.execPath, ["scripts/createLanguageServicesBuild.js"]);
task("create-language-services-build", series(buildScripts, createLanguageServicesBuild));
task("create-language-services-build").description = "Runs scripts/createLanguageServicesBuild.ts to prepare a build which only has the require('typescript') JS.";
const configureExperimental = () => exec(process.execPath, ["scripts/configurePrerelease.mjs", "experimental", "package.json", "src/compiler/corePublic.ts"]);
task("configure-experimental", configureExperimental);
task("configure-experimental").description = "Runs scripts/configurePrerelease.mjs to prepare a build for experimental publishing";
const publishNightly = () => exec("npm", ["publish", "--tag", "next"]);
task("publish-nightly", series(task("clean"), task("LKG"), task("clean"), task("runtests-parallel"), publishNightly));
+55 -54
View File
@@ -69,7 +69,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
var ts;
(function (ts) {
ts.versionMajorMinor = "4.8";
ts.version = "4.8.3";
ts.version = "4.8.4";
var NativeCollections;
(function (NativeCollections) {
var globals = typeof globalThis !== "undefined" ? globalThis :
@@ -25457,6 +25457,7 @@ var ts;
case 335:
case 336:
case 331:
case 337:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350:
@@ -34938,7 +34939,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -36067,13 +36068,13 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
return packageJsonInfo.resolvedEntrypoints;
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -36081,13 +36082,13 @@ var ts;
var requireState = getTemporaryModuleResolutionState(cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), host, options);
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -36096,7 +36097,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -36192,7 +36193,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -36208,7 +36211,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -36320,17 +36323,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName);
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -36338,30 +36340,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, false);
return loadModuleFromTargetImportOrExport(mainExport, "", false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, false);
if (result) {
return result;
}
@@ -36379,8 +36381,7 @@ var ts;
}
return toSearchResult(undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -36388,13 +36389,13 @@ var ts;
}
return toSearchResult(undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, true);
if (result) {
return result;
}
@@ -36691,20 +36692,20 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
pathAndExtension = loadModuleFromFile(extensions, ts.combinePaths(candidate, "index.js"), onlyRecordFailures, state);
}
@@ -36713,12 +36714,12 @@ var ts;
if (rest !== "") {
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -40287,6 +40288,7 @@ var ts;
var wildcardType = createIntrinsicType(1, "any");
var errorType = createIntrinsicType(1, "error");
var unresolvedType = createIntrinsicType(1, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1, "any", 65536);
var intrinsicMarkerType = createIntrinsicType(1, "intrinsic");
var unknownType = createIntrinsicType(2, "unknown");
var nonNullUnknownType = createIntrinsicType(2, "unknown");
@@ -42545,7 +42547,7 @@ var ts;
if (ext === ".ts" || ext === ".js" || ext === ".tsx" || ext === ".jsx") {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" ? ".mts" : ext === ".js" ? ".mjs" : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
}
@@ -44559,19 +44561,14 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, undefined, visited.propertyName, undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -47113,7 +47110,7 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
return includePatternInType ? nonInferrableAnyType : anyType;
}
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
var members = ts.createSymbolTable();
@@ -48941,6 +48938,10 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152) {
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 | 8 | 64)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -57813,7 +57814,7 @@ var ts;
}
var inference = getInferenceInfoForType(target);
if (inference) {
if (ts.getObjectFlags(source) & 262144) {
if (ts.getObjectFlags(source) & 262144 || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -68354,7 +68355,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -76001,7 +76002,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
var assertionArgument = nodeArguments[1];
@@ -97471,7 +97472,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -98966,7 +98967,7 @@ var ts;
return result;
}
function getCreateSourceFileOptions(fileName, moduleResolutionCache, host, options) {
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -102976,7 +102977,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -103308,7 +103309,7 @@ var ts;
break;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, file.packageJsonScope.packageJsonContent.type ?
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
+67 -59
View File
@@ -109,7 +109,7 @@ var ts;
// The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
ts.version = "4.8.3";
ts.version = "4.8.4";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -31516,6 +31516,7 @@ var ts;
case 335 /* SyntaxKind.JSDocProtectedTag */:
case 336 /* SyntaxKind.JSDocReadonlyTag */:
case 331 /* SyntaxKind.JSDocDeprecatedTag */:
case 337 /* SyntaxKind.JSDocOverrideTag */:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350 /* SyntaxKind.PartiallyEmittedExpression */:
@@ -42804,7 +42805,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -44123,16 +44124,16 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/* @internal */
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
// Cached value excludes resolutions to JS files - those could be
// cached separately, but they're used rarely.
return packageJsonInfo.resolvedEntrypoints;
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -44141,13 +44142,13 @@ var ts;
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory,
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -44156,7 +44157,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -44260,7 +44261,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -44276,7 +44279,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -44401,17 +44404,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -44419,30 +44421,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false);
if (result) {
return result;
}
@@ -44460,8 +44462,7 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -44469,13 +44470,13 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true);
if (result) {
return result;
}
@@ -44820,7 +44821,7 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
@@ -44828,14 +44829,14 @@ var ts;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
// package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
// eslint-disable-next-line no-null/no-null
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
// EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
// a default `index.js` entrypoint if no `main` or `exports` are present
@@ -44847,12 +44848,12 @@ var ts;
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -49153,6 +49154,7 @@ var ts;
var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any");
var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error");
var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */);
var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic");
var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
@@ -51754,7 +51756,7 @@ var ts;
if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(
/*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
@@ -53982,22 +53984,15 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken,
/* propertyName*/ undefined, visited.propertyName,
/*initializer*/ undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -56992,7 +56987,11 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
// When we're including the pattern in the type (an indication we're obtaining a contextual type), we
// use a non-inferrable any type. Inference will never directly infer this type, but it is possible
// to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
// widening of the binding pattern type substitutes a regular any for the non-inferrable any.
return includePatternInType ? nonInferrableAnyType : anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
@@ -59093,6 +59092,12 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* TypeFlags.Intersection */) {
// Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {},
// and bigint & {} intersections that are used to prevent subtype reduction in union types.
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -69280,7 +69285,10 @@ var ts;
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) {
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -81446,7 +81454,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -90225,7 +90233,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
// We are allowed trailing comma after proposal-import-assertions.
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
@@ -117872,7 +117880,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -119603,7 +119611,7 @@ var ts;
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -124264,7 +124272,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -124626,7 +124634,7 @@ var ts;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(
/*details*/ undefined, file.packageJsonScope.packageJsonContent.type ?
/*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
@@ -141362,7 +141370,7 @@ var ts;
}
var parent = node.parent;
var typeChecker = program.getTypeChecker();
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) {
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) {
return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray;
}
// Labels
@@ -178842,7 +178850,7 @@ var ts;
var packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex);
var packageJsonCache = (_a = project.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache();
var compilerOptions = project.getCompilationSettings();
var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
var packageJson = ts.getPackageScopeForPath(ts.getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
if (!packageJson)
return undefined;
// Use fake options instead of actual compiler options to avoid following export map if the project uses node16 or nodenext -
+67 -59
View File
@@ -303,7 +303,7 @@ var ts;
// The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
ts.version = "4.8.3";
ts.version = "4.8.4";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -31710,6 +31710,7 @@ var ts;
case 335 /* SyntaxKind.JSDocProtectedTag */:
case 336 /* SyntaxKind.JSDocReadonlyTag */:
case 331 /* SyntaxKind.JSDocDeprecatedTag */:
case 337 /* SyntaxKind.JSDocOverrideTag */:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350 /* SyntaxKind.PartiallyEmittedExpression */:
@@ -42998,7 +42999,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -44317,16 +44318,16 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/* @internal */
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
// Cached value excludes resolutions to JS files - those could be
// cached separately, but they're used rarely.
return packageJsonInfo.resolvedEntrypoints;
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -44335,13 +44336,13 @@ var ts;
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory,
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -44350,7 +44351,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -44454,7 +44455,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -44470,7 +44473,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -44595,17 +44598,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -44613,30 +44615,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false);
if (result) {
return result;
}
@@ -44654,8 +44656,7 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -44663,13 +44664,13 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true);
if (result) {
return result;
}
@@ -45014,7 +45015,7 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
@@ -45022,14 +45023,14 @@ var ts;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
// package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
// eslint-disable-next-line no-null/no-null
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
// EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
// a default `index.js` entrypoint if no `main` or `exports` are present
@@ -45041,12 +45042,12 @@ var ts;
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -49347,6 +49348,7 @@ var ts;
var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any");
var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error");
var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */);
var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic");
var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
@@ -51948,7 +51950,7 @@ var ts;
if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(
/*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
@@ -54176,22 +54178,15 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken,
/* propertyName*/ undefined, visited.propertyName,
/*initializer*/ undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -57186,7 +57181,11 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
// When we're including the pattern in the type (an indication we're obtaining a contextual type), we
// use a non-inferrable any type. Inference will never directly infer this type, but it is possible
// to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
// widening of the binding pattern type substitutes a regular any for the non-inferrable any.
return includePatternInType ? nonInferrableAnyType : anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
@@ -59287,6 +59286,12 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* TypeFlags.Intersection */) {
// Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {},
// and bigint & {} intersections that are used to prevent subtype reduction in union types.
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -69474,7 +69479,10 @@ var ts;
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) {
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -81640,7 +81648,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -90419,7 +90427,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
// We are allowed trailing comma after proposal-import-assertions.
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
@@ -118066,7 +118074,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -119797,7 +119805,7 @@ var ts;
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -124458,7 +124466,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -124820,7 +124828,7 @@ var ts;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(
/*details*/ undefined, file.packageJsonScope.packageJsonContent.type ?
/*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
@@ -141975,7 +141983,7 @@ var ts;
}
var parent = node.parent;
var typeChecker = program.getTypeChecker();
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) {
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) {
return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray;
}
// Labels
@@ -179036,7 +179044,7 @@ var ts;
var packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex);
var packageJsonCache = (_a = project.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache();
var compilerOptions = project.getCompilationSettings();
var packageJson = ts.getPackageScopeForPath(project.toPath(packageDirectory + "/package.json"), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
var packageJson = ts.getPackageScopeForPath(ts.getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), ts.getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions));
if (!packageJson)
return undefined;
// Use fake options instead of actual compiler options to avoid following export map if the project uses node16 or nodenext -
+66 -58
View File
@@ -294,7 +294,7 @@ var ts;
// The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
ts.version = "4.8.3";
ts.version = "4.8.4";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -31701,6 +31701,7 @@ var ts;
case 335 /* SyntaxKind.JSDocProtectedTag */:
case 336 /* SyntaxKind.JSDocReadonlyTag */:
case 331 /* SyntaxKind.JSDocDeprecatedTag */:
case 337 /* SyntaxKind.JSDocOverrideTag */:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350 /* SyntaxKind.PartiallyEmittedExpression */:
@@ -42989,7 +42990,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -44308,16 +44309,16 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/* @internal */
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
// Cached value excludes resolutions to JS files - those could be
// cached separately, but they're used rarely.
return packageJsonInfo.resolvedEntrypoints;
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -44326,13 +44327,13 @@ var ts;
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory,
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -44341,7 +44342,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -44445,7 +44446,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -44461,7 +44464,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -44586,17 +44589,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -44604,30 +44606,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false);
if (result) {
return result;
}
@@ -44645,8 +44647,7 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -44654,13 +44655,13 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true);
if (result) {
return result;
}
@@ -45005,7 +45006,7 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
@@ -45013,14 +45014,14 @@ var ts;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
// package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
// eslint-disable-next-line no-null/no-null
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
// EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
// a default `index.js` entrypoint if no `main` or `exports` are present
@@ -45032,12 +45033,12 @@ var ts;
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -49338,6 +49339,7 @@ var ts;
var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any");
var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error");
var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */);
var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic");
var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
@@ -51939,7 +51941,7 @@ var ts;
if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(
/*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
@@ -54167,22 +54169,15 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken,
/* propertyName*/ undefined, visited.propertyName,
/*initializer*/ undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -57177,7 +57172,11 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
// When we're including the pattern in the type (an indication we're obtaining a contextual type), we
// use a non-inferrable any type. Inference will never directly infer this type, but it is possible
// to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
// widening of the binding pattern type substitutes a regular any for the non-inferrable any.
return includePatternInType ? nonInferrableAnyType : anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
@@ -59278,6 +59277,12 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* TypeFlags.Intersection */) {
// Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {},
// and bigint & {} intersections that are used to prevent subtype reduction in union types.
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -69465,7 +69470,10 @@ var ts;
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) {
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -81631,7 +81639,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -90410,7 +90418,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
// We are allowed trailing comma after proposal-import-assertions.
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
@@ -118057,7 +118065,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -119788,7 +119796,7 @@ var ts;
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -124449,7 +124457,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -124811,7 +124819,7 @@ var ts;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(
/*details*/ undefined, file.packageJsonScope.packageJsonContent.type ?
/*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
@@ -141966,7 +141974,7 @@ var ts;
}
var parent = node.parent;
var typeChecker = program.getTypeChecker();
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) {
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) {
return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray;
}
// Labels
+66 -58
View File
@@ -294,7 +294,7 @@ var ts;
// The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
ts.version = "4.8.3";
ts.version = "4.8.4";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -31701,6 +31701,7 @@ var ts;
case 335 /* SyntaxKind.JSDocProtectedTag */:
case 336 /* SyntaxKind.JSDocReadonlyTag */:
case 331 /* SyntaxKind.JSDocDeprecatedTag */:
case 337 /* SyntaxKind.JSDocOverrideTag */:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350 /* SyntaxKind.PartiallyEmittedExpression */:
@@ -42989,7 +42990,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -44308,16 +44309,16 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/* @internal */
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
// Cached value excludes resolutions to JS files - those could be
// cached separately, but they're used rarely.
return packageJsonInfo.resolvedEntrypoints;
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -44326,13 +44327,13 @@ var ts;
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory,
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -44341,7 +44342,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -44445,7 +44446,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -44461,7 +44464,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -44586,17 +44589,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -44604,30 +44606,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false);
if (result) {
return result;
}
@@ -44645,8 +44647,7 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -44654,13 +44655,13 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true);
if (result) {
return result;
}
@@ -45005,7 +45006,7 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
@@ -45013,14 +45014,14 @@ var ts;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
// package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
// eslint-disable-next-line no-null/no-null
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
// EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
// a default `index.js` entrypoint if no `main` or `exports` are present
@@ -45032,12 +45033,12 @@ var ts;
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -49338,6 +49339,7 @@ var ts;
var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any");
var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error");
var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */);
var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic");
var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
@@ -51939,7 +51941,7 @@ var ts;
if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(
/*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
@@ -54167,22 +54169,15 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken,
/* propertyName*/ undefined, visited.propertyName,
/*initializer*/ undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -57177,7 +57172,11 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
// When we're including the pattern in the type (an indication we're obtaining a contextual type), we
// use a non-inferrable any type. Inference will never directly infer this type, but it is possible
// to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
// widening of the binding pattern type substitutes a regular any for the non-inferrable any.
return includePatternInType ? nonInferrableAnyType : anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
@@ -59278,6 +59277,12 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* TypeFlags.Intersection */) {
// Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {},
// and bigint & {} intersections that are used to prevent subtype reduction in union types.
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -69465,7 +69470,10 @@ var ts;
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) {
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -81631,7 +81639,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -90410,7 +90418,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
// We are allowed trailing comma after proposal-import-assertions.
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
@@ -118057,7 +118065,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -119788,7 +119796,7 @@ var ts;
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -124449,7 +124457,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -124811,7 +124819,7 @@ var ts;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(
/*details*/ undefined, file.packageJsonScope.packageJsonContent.type ?
/*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
@@ -141966,7 +141974,7 @@ var ts;
}
var parent = node.parent;
var typeChecker = program.getTypeChecker();
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isJSDocOverrideTag(node) && ts.rangeContainsPosition(node.tagName, position))) {
if (node.kind === 159 /* SyntaxKind.OverrideKeyword */ || (ts.isIdentifier(node) && ts.isJSDocOverrideTag(parent) && parent.tagName === node)) {
return getDefinitionFromOverriddenMember(typeChecker, node) || ts.emptyArray;
}
// Labels
+65 -57
View File
@@ -89,7 +89,7 @@ var ts;
// The following is baselined as a literal template type without intervention
/** The version of the TypeScript compiler release */
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
ts.version = "4.8.3";
ts.version = "4.8.4";
/* @internal */
var Comparison;
(function (Comparison) {
@@ -31496,6 +31496,7 @@ var ts;
case 335 /* SyntaxKind.JSDocProtectedTag */:
case 336 /* SyntaxKind.JSDocReadonlyTag */:
case 331 /* SyntaxKind.JSDocDeprecatedTag */:
case 337 /* SyntaxKind.JSDocOverrideTag */:
return visitNode(cbNode, node.tagName)
|| (typeof node.comment === "string" ? undefined : visitNodes(cbNode, cbNodes, node.comment));
case 350 /* SyntaxKind.PartiallyEmittedExpression */:
@@ -42784,7 +42785,7 @@ var ts;
function withPackageId(packageInfo, r) {
var packageId;
if (r && packageInfo) {
var packageJsonContent = packageInfo.packageJsonContent;
var packageJsonContent = packageInfo.contents.packageJsonContent;
if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
packageId = {
name: packageJsonContent.name,
@@ -44103,16 +44104,16 @@ var ts;
function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
if (considerPackageJson === void 0) { considerPackageJson = true; }
var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
var versionPaths = packageInfo && packageInfo.versionPaths;
var packageJsonContent = packageInfo && packageInfo.contents.packageJsonContent;
var versionPaths = packageInfo && packageInfo.contents.versionPaths;
return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
}
/* @internal */
function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) {
if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) {
if (!resolveJs && packageJsonInfo.contents.resolvedEntrypoints !== undefined) {
// Cached value excludes resolutions to JS files - those could be
// cached separately, but they're used rarely.
return packageJsonInfo.resolvedEntrypoints;
return packageJsonInfo.contents.resolvedEntrypoints;
}
var entrypoints;
var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript;
@@ -44121,13 +44122,13 @@ var ts;
requireState.conditions = ["node", "require", "types"];
requireState.requestContainingDirectory = packageJsonInfo.packageDirectory;
var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory,
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths);
/*onlyRecordFailures*/ false, requireState, packageJsonInfo.contents.packageJsonContent, packageJsonInfo.contents.versionPaths);
entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path);
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) {
if (features & NodeResolutionFeatures.Exports && packageJsonInfo.contents.packageJsonContent.exports) {
for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) {
var conditions = _a[_i];
var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions });
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions);
var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.contents.packageJsonContent.exports, exportState, extensions);
if (exportResolutions) {
for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) {
var resolution = exportResolutions_1[_b];
@@ -44136,7 +44137,7 @@ var ts;
}
}
}
return packageJsonInfo.resolvedEntrypoints = entrypoints || false;
return packageJsonInfo.contents.resolvedEntrypoints = entrypoints || false;
}
ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo;
function loadEntrypointsFromExportMap(scope, exports, state, extensions) {
@@ -44240,7 +44241,9 @@ var ts;
if (traceEnabled)
trace(host, ts.Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath);
state.affectingLocations.push(packageJsonPath);
return existing;
return existing.packageDirectory === packageDirectory ?
existing :
{ packageDirectory: packageDirectory, contents: existing.contents };
}
else {
if (existing && traceEnabled)
@@ -44256,7 +44259,7 @@ var ts;
trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
}
var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined };
var result = { packageDirectory: packageDirectory, contents: { packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined } };
(_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result);
state.affectingLocations.push(packageJsonPath);
return result;
@@ -44381,17 +44384,16 @@ var ts;
}
function loadModuleFromSelfNameReference(extensions, moduleName, directory, state, cache, redirectedReference) {
var _a, _b;
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope || !scope.packageJsonContent.exports) {
if (!scope || !scope.contents.packageJsonContent.exports) {
return undefined;
}
if (typeof scope.packageJsonContent.name !== "string") {
if (typeof scope.contents.packageJsonContent.name !== "string") {
return undefined;
}
var parts = ts.getPathComponents(moduleName); // unrooted paths should have `""` as their 0th entry
var nameParts = ts.getPathComponents(scope.packageJsonContent.name);
var nameParts = ts.getPathComponents(scope.contents.packageJsonContent.name);
if (!ts.every(nameParts, function (p, i) { return parts[i] === p; })) {
return undefined;
}
@@ -44399,30 +44401,30 @@ var ts;
return loadModuleFromExports(scope, extensions, !ts.length(trailingParts) ? "." : ".".concat(ts.directorySeparator).concat(trailingParts.join(ts.directorySeparator)), state, cache, redirectedReference);
}
function loadModuleFromExports(scope, extensions, subpath, state, cache, redirectedReference) {
if (!scope.packageJsonContent.exports) {
if (!scope.contents.packageJsonContent.exports) {
return undefined;
}
if (subpath === ".") {
var mainExport = void 0;
if (typeof scope.packageJsonContent.exports === "string" || Array.isArray(scope.packageJsonContent.exports) || (typeof scope.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.packageJsonContent.exports))) {
mainExport = scope.packageJsonContent.exports;
if (typeof scope.contents.packageJsonContent.exports === "string" || Array.isArray(scope.contents.packageJsonContent.exports) || (typeof scope.contents.packageJsonContent.exports === "object" && noKeyStartsWithDot(scope.contents.packageJsonContent.exports))) {
mainExport = scope.contents.packageJsonContent.exports;
}
else if (ts.hasProperty(scope.packageJsonContent.exports, ".")) {
mainExport = scope.packageJsonContent.exports["."];
else if (ts.hasProperty(scope.contents.packageJsonContent.exports, ".")) {
mainExport = scope.contents.packageJsonContent.exports["."];
}
if (mainExport) {
var loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, subpath, scope, /*isImports*/ false);
return loadModuleFromTargetImportOrExport(mainExport, "", /*pattern*/ false);
}
}
else if (allKeysStartWithDot(scope.packageJsonContent.exports)) {
if (typeof scope.packageJsonContent.exports !== "object") {
else if (allKeysStartWithDot(scope.contents.packageJsonContent.exports)) {
if (typeof scope.contents.packageJsonContent.exports !== "object") {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.Export_specifier_0_does_not_exist_in_package_json_scope_at_path_1, subpath, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.packageJsonContent.exports, scope, /*isImports*/ false);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, subpath, scope.contents.packageJsonContent.exports, scope, /*isImports*/ false);
if (result) {
return result;
}
@@ -44440,8 +44442,7 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
var useCaseSensitiveFileNames = typeof state.host.useCaseSensitiveFileNames === "function" ? state.host.useCaseSensitiveFileNames() : state.host.useCaseSensitiveFileNames;
var directoryPath = ts.toPath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a), ts.createGetCanonicalFileName(useCaseSensitiveFileNames === undefined ? true : useCaseSensitiveFileNames));
var directoryPath = ts.getNormalizedAbsolutePath(ts.combinePaths(directory, "dummy"), (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a));
var scope = getPackageScopeForPath(directoryPath, state);
if (!scope) {
if (state.traceEnabled) {
@@ -44449,13 +44450,13 @@ var ts;
}
return toSearchResult(/*value*/ undefined);
}
if (!scope.packageJsonContent.imports) {
if (!scope.contents.packageJsonContent.imports) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_scope_0_has_no_imports_defined, scope.packageDirectory);
}
return toSearchResult(/*value*/ undefined);
}
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.packageJsonContent.imports, scope, /*isImports*/ true);
var result = loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, scope.contents.packageJsonContent.imports, scope, /*isImports*/ true);
if (result) {
return result;
}
@@ -44800,7 +44801,7 @@ var ts;
if (fromFile) {
return noPackageId(fromFile);
}
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.contents.packageJsonContent, packageInfo.contents.versionPaths);
return withPackageId(packageInfo, fromDirectory);
}
}
@@ -44808,14 +44809,14 @@ var ts;
var loader = function (extensions, candidate, onlyRecordFailures, state) {
var _a;
// package exports are higher priority than file/directory lookups (and, if there's exports present, blocks them)
if (packageInfo && packageInfo.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
if (packageInfo && packageInfo.contents.packageJsonContent.exports && state.features & NodeResolutionFeatures.Exports) {
return (_a = loadModuleFromExports(packageInfo, extensions, ts.combinePaths(".", rest), state, cache, redirectedReference)) === null || _a === void 0 ? void 0 : _a.value;
}
var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.contents.packageJsonContent, packageInfo && packageInfo.contents.versionPaths);
if (!pathAndExtension && packageInfo
// eslint-disable-next-line no-null/no-null
&& (packageInfo.packageJsonContent.exports === undefined || packageInfo.packageJsonContent.exports === null)
&& (packageInfo.contents.packageJsonContent.exports === undefined || packageInfo.contents.packageJsonContent.exports === null)
&& state.features & NodeResolutionFeatures.EsmMode) {
// EsmMode disables index lookup in `loadNodeModuleFromDirectoryWorker` generally, however non-relative package resolutions still assume
// a default `index.js` entrypoint if no `main` or `exports` are present
@@ -44827,12 +44828,12 @@ var ts;
var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
// Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings.
packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
if (packageInfo && packageInfo.versionPaths) {
if (packageInfo && packageInfo.contents.versionPaths) {
if (state.traceEnabled) {
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.versionPaths.version, ts.version, rest);
trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, packageInfo.contents.versionPaths.version, ts.version, rest);
}
var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.contents.versionPaths.paths, /*pathPatterns*/ undefined, loader, !packageDirectoryExists, state);
if (fromPaths) {
return fromPaths.value;
}
@@ -49133,6 +49134,7 @@ var ts;
var wildcardType = createIntrinsicType(1 /* TypeFlags.Any */, "any");
var errorType = createIntrinsicType(1 /* TypeFlags.Any */, "error");
var unresolvedType = createIntrinsicType(1 /* TypeFlags.Any */, "unresolved");
var nonInferrableAnyType = createIntrinsicType(1 /* TypeFlags.Any */, "any", 65536 /* ObjectFlags.ContainsWideningType */);
var intrinsicMarkerType = createIntrinsicType(1 /* TypeFlags.Any */, "intrinsic");
var unknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
var nonNullUnknownType = createIntrinsicType(2 /* TypeFlags.Unknown */, "unknown");
@@ -51734,7 +51736,7 @@ var ts;
if (ext === ".ts" /* Extension.Ts */ || ext === ".js" /* Extension.Js */ || ext === ".tsx" /* Extension.Tsx */ || ext === ".jsx" /* Extension.Jsx */) {
var scope = currentSourceFile.packageJsonScope;
var targetExt = ext === ".ts" /* Extension.Ts */ ? ".mts" /* Extension.Mts */ : ext === ".js" /* Extension.Js */ ? ".mjs" /* Extension.Mjs */ : undefined;
if (scope && !scope.packageJsonContent.type) {
if (scope && !scope.contents.packageJsonContent.type) {
if (targetExt) {
diagnosticDetails = ts.chainDiagnosticMessages(
/*details*/ undefined, ts.Diagnostics.To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Colon_module_to_1, targetExt, ts.combinePaths(scope.packageDirectory, "package.json"));
@@ -53962,22 +53964,15 @@ var ts;
context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
return parameterNode;
function cloneBindingName(node) {
return elideInitializerAndPropertyRenamingAndSetEmitFlags(node);
function elideInitializerAndPropertyRenamingAndSetEmitFlags(node) {
return elideInitializerAndSetEmitFlags(node);
function elideInitializerAndSetEmitFlags(node) {
if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
trackComputedName(node.expression, context.enclosingDeclaration, context);
}
var visited = ts.visitEachChild(node, elideInitializerAndPropertyRenamingAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndPropertyRenamingAndSetEmitFlags);
var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
if (ts.isBindingElement(visited)) {
if (visited.propertyName && ts.isIdentifier(visited.propertyName) && ts.isIdentifier(visited.name)) {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken,
/* propertyName*/ undefined, visited.propertyName,
/*initializer*/ undefined);
}
else {
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name,
/*initializer*/ undefined);
}
if (!ts.nodeIsSynthesized(visited)) {
visited = ts.factory.cloneNode(visited);
@@ -56972,7 +56967,11 @@ var ts;
if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
reportImplicitAny(element, anyType);
}
return anyType;
// When we're including the pattern in the type (an indication we're obtaining a contextual type), we
// use a non-inferrable any type. Inference will never directly infer this type, but it is possible
// to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
// widening of the binding pattern type substitutes a regular any for the non-inferrable any.
return includePatternInType ? nonInferrableAnyType : anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
@@ -59073,6 +59072,12 @@ var ts;
return mapType(type, getLowerBoundOfKeyType);
}
if (type.flags & 2097152 /* TypeFlags.Intersection */) {
// Similarly to getTypeFromIntersectionTypeNode, we preserve the special string & {}, number & {},
// and bigint & {} intersections that are used to prevent subtype reduction in union types.
var types = type.types;
if (types.length === 2 && !!(types[0].flags & (4 /* TypeFlags.String */ | 8 /* TypeFlags.Number */ | 64 /* TypeFlags.BigInt */)) && types[1] === emptyTypeLiteralType) {
return type;
}
return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
}
return type;
@@ -69260,7 +69265,10 @@ var ts;
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */) {
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if (ts.getObjectFlags(source) & 262144 /* ObjectFlags.NonInferrableType */ || source === nonInferrableAnyType) {
return;
}
if (!inference.isFixed) {
@@ -81426,7 +81434,7 @@ var ts;
checkDecorators(node);
}
function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
if (index < typeParameters.length) {
if (node.typeArguments && index < node.typeArguments.length) {
return getTypeFromTypeNode(node.typeArguments[index]);
}
return getEffectiveTypeArguments(node, typeParameters)[index];
@@ -90205,7 +90213,7 @@ var ts;
return grammarErrorOnNode(node, ts.Diagnostics.This_use_of_import_is_invalid_import_calls_can_be_written_but_they_must_have_parentheses_and_cannot_have_type_arguments);
}
var nodeArguments = node.arguments;
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) {
if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext && moduleKind !== ts.ModuleKind.Node16) {
// We are allowed trailing comma after proposal-import-assertions.
checkGrammarForDisallowedTrailingComma(nodeArguments);
if (nodeArguments.length > 1) {
@@ -117852,7 +117860,7 @@ var ts;
state.failedLookupLocations = packageJsonLocations;
state.affectingLocations = packageJsonLocations;
var packageJsonScope = ts.getPackageScopeForPath(fileName, state);
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
var impliedNodeFormat = (packageJsonScope === null || packageJsonScope === void 0 ? void 0 : packageJsonScope.contents.packageJsonContent.type) === "module" ? ts.ModuleKind.ESNext : ts.ModuleKind.CommonJS;
return { impliedNodeFormat: impliedNodeFormat, packageJsonLocations: packageJsonLocations, packageJsonScope: packageJsonScope };
}
}
@@ -119583,7 +119591,7 @@ var ts;
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
var result = getImpliedNodeFormatForFileWorker(toPath(fileName), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var result = getImpliedNodeFormatForFileWorker(ts.getNormalizedAbsolutePath(fileName, currentDirectory), moduleResolutionCache === null || moduleResolutionCache === void 0 ? void 0 : moduleResolutionCache.getPackageJsonInfoCache(), host, options);
var languageVersion = ts.getEmitScriptTarget(options);
var setExternalModuleIndicator = ts.getSetExternalModuleIndicator(options);
return typeof result === "object" ? __assign(__assign({}, result), { languageVersion: languageVersion, setExternalModuleIndicator: setExternalModuleIndicator }) :
@@ -124244,7 +124252,7 @@ var ts;
var maybeBlockedByTypesVersions = false;
var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath);
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.contents.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath));
var importMode = overrideMode || importingSourceFile.impliedNodeFormat;
if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node16 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) {
var conditions = ["node", importMode === ts.ModuleKind.ESNext ? "import" : "require", "types"];
@@ -124606,7 +124614,7 @@ var ts;
case ts.ModuleKind.CommonJS:
if (file.packageJsonScope) {
(result !== null && result !== void 0 ? result : (result = [])).push(ts.chainDiagnosticMessages(
/*details*/ undefined, file.packageJsonScope.packageJsonContent.type ?
/*details*/ undefined, file.packageJsonScope.contents.packageJsonContent.type ?
ts.Diagnostics.File_is_CommonJS_module_because_0_has_field_type_whose_value_is_not_module :
ts.Diagnostics.File_is_CommonJS_module_because_0_does_not_have_field_type, toFileName(ts.last(file.packageJsonLocations), fileNameConvertor)));
}
+731 -507
View File
File diff suppressed because it is too large Load Diff
+5 -4
View File
@@ -41,6 +41,7 @@
"devDependencies": {
"@octokit/rest": "latest",
"@types/chai": "latest",
"@types/fancy-log": "^2.0.0",
"@types/fs-extra": "^9.0.13",
"@types/glob": "latest",
"@types/gulp": "^4.0.9",
@@ -55,8 +56,8 @@
"@types/mocha": "latest",
"@types/ms": "latest",
"@types/node": "latest",
"@types/node-fetch": "^2.6.2",
"@types/source-map-support": "latest",
"@types/which": "^2.0.1",
"@types/xml2js": "^0.4.11",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
@@ -87,9 +88,9 @@
"mocha": "latest",
"mocha-fivemat-progress-reporter": "latest",
"ms": "^2.1.3",
"node-fetch": "^2.6.7",
"node-fetch": "^3.2.10",
"source-map-support": "latest",
"typescript": "^4.8.3",
"typescript": "^4.8.4",
"vinyl": "latest",
"which": "^2.0.2",
"xml2js": "^0.4.23"
@@ -107,7 +108,7 @@
"clean": "gulp clean",
"gulp": "gulp",
"lint": "gulp lint",
"setup-hooks": "node scripts/link-hooks.js"
"setup-hooks": "node scripts/link-hooks.mjs"
},
"browser": {
"fs": false,
-75
View File
@@ -1,75 +0,0 @@
<#
.SYNOPSIS
Run this PowerShell script to enable dev mode and/or a custom script for the TypeScript language service, e.g.
PS C:\> .\scripts\VSDevMode.ps1 -enableDevMode -tsScript C:\src\TypeScript\built\local\
Note: If you get security errors, try running powershell as an Administrator and with the "-executionPolicy remoteSigned" switch
.PARAMETER vsVersion
Set to "12" for Dev12 (VS2013) or "14" (the default) for Dev14 (VS2015)
.PARAMETER enableDevMode
Pass this switch to enable attaching a debugger to the language service
.PARAMETER tsScript
The path to a directory containing a custom language service script to use (typescriptServices.js), e.g. "C:\src\TypeScript\built\local\"
#>
Param(
[int]$vsVersion = 14,
[switch]$enableDevMode,
[string]$tsScript
)
$vsRegKey = "HKCU:\Software\Microsoft\VisualStudio\${vsVersion}.0"
$tsRegKey = "${vsRegKey}\TypeScriptLanguageService"
if($enableDevMode -ne $true -and $tsScript -eq ""){
Throw "You must either enable language service debugging (-enableDevMode), set a custom script (-tsScript), or both"
}
if(!(Test-Path $vsRegKey)){
Throw "Visual Studio ${vsVersion} is not installed"
}
if(!(Test-Path $tsRegKey)){
# Create the TypeScript subkey if it doesn't exist
New-Item -path $tsRegKey
}
if($tsScript -ne ""){
$tsScriptServices = "${tsScript}\typescriptServices.js"
$tsScriptlib = "${tsScript}\lib.d.ts"
$tsES6Scriptlib = "${tsScript}\lib.es6.d.ts"
if(!(Test-Path $tsScriptServices)){
Throw "Could not locate the TypeScript language service script at ${tsScriptServices}"
}
else {
$path = resolve-path ${tsScriptServices}
Set-ItemProperty -path $tsRegKey -name CustomTypeScriptServicesFileLocation -value "${path}"
Write-Host "Enabled custom TypeScript language service at ${path} for Dev${vsVersion}"
}
if(!(Test-Path $tsScriptlib)){
Throw "Could not locate the TypeScript default library at ${tsScriptlib}"
}
else {
$path = resolve-path ${tsScriptlib}
Set-ItemProperty -path $tsRegKey -name CustomDefaultLibraryLocation -value "${path}"
Write-Host "Enabled custom TypeScript default library at ${path} for Dev${vsVersion}"
}
if(!(Test-Path $tsES6Scriptlib)){
Throw "Could not locate the TypeScript default ES6 library at ${tsES6Scriptlib}"
}
else {
$path = resolve-path ${tsES6Scriptlib}
Set-ItemProperty -path $tsRegKey -name CustomDefaultES6LibraryLocation -value "${path}"
Write-Host "Enabled custom TypeScript default ES6 library at ${path} for Dev${vsVersion}"
}
}
if($enableDevMode){
Set-ItemProperty -path $tsRegKey -name EnableDevMode -value 1
Write-Host "Enabled developer mode for Dev${vsVersion}"
}
@@ -1,34 +1,36 @@
// @ts-check
const chalk = require("chalk");
const { join } = require("path");
const { readFileSync } = require("fs");
import chalk from "chalk";
import { join } from "path";
import { readFileSync } from "fs";
let playwright;
try {
// eslint-disable-next-line import/no-extraneous-dependencies
require("playwright");
// @ts-ignore-error
playwright = await import("playwright");
}
catch (error) {
throw new Error("Playwright is expected to be installed manually before running this script");
}
// eslint-disable-next-line import/no-extraneous-dependencies
const playwright = require("playwright");
// Turning this on will leave the Chromium browser open, giving you the
// chance to open up the web inspector.
const debugging = false;
(async () => {
for (const browserType of ["chromium", "firefox"]) {
/** @type {["chromium", "firefox"]} */
const browsers = ["chromium", "firefox"];
for (const browserType of browsers) {
const browser = await playwright[browserType].launch({ headless: !debugging });
const context = await browser.newContext();
const page = await context.newPage();
/** @type {(err: Error) => void} */
const errorCaught = err => {
console.error(chalk.red("There was an error running built/typescript.js in " + browserType));
console.log(err.toString());
process.exitCode = 1;
};
// @ts-ignore-error
page.on("error", errorCaught);
page.on("pageerror", errorCaught);
@@ -45,13 +47,4 @@ const debugging = false;
console.log("Not closing the browser, you'll need to exit the process in your terminal manually");
}
console.log(`${browserType} :+1:`);
}
})();
process.on("unhandledRejection", (/** @type {any}*/ err) => {
if (err) {
console.error(err.stack || err.message);
}
process.exit(1);
});
}
-21
View File
@@ -1,21 +0,0 @@
const { join, resolve, dirname } = require("path");
const { existsSync } = require("fs");
// search directories upward to avoid hard-wired paths based on the
// build tree (same as src/harness/findUpDir.ts)
function findUpFile(name) {
let dir = __dirname;
while (true) {
const fullPath = join(dir, name);
if (existsSync(fullPath)) return fullPath;
const up = resolve(dir, "..");
if (up === dir) return name; // it'll fail anyway
dir = up;
}
}
exports.findUpFile = findUpFile;
const findUpRoot = () =>
findUpRoot.cached || (findUpRoot.cached = dirname(findUpFile("Gulpfile.js")));
exports.findUpRoot = findUpRoot;
+29
View File
@@ -0,0 +1,29 @@
import { join, resolve, dirname } from "path";
import { existsSync } from "fs";
import url from "url";
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = dirname(__filename);
// search directories upward to avoid hard-wired paths based on the
// build tree (same as src/harness/findUpDir.ts)
/**
* @param {string} name
* @returns {string}
*/
export function findUpFile(name) {
let dir = __dirname;
while (true) {
const fullPath = join(dir, name);
if (existsSync(fullPath)) return fullPath;
const up = resolve(dir, "..");
if (up === dir) return name; // it'll fail anyway
dir = up;
}
}
/** @type {string | undefined} */
let findUpRootCache;
export const findUpRoot = () => findUpRootCache || (findUpRootCache = dirname(findUpFile("Gulpfile.mjs")));
@@ -1,11 +1,9 @@
// @ts-check
const minimist = require("minimist");
const os = require("os");
import minimist from "minimist";
import os from "os";
const ci = ["1", "true"].includes(process.env.CI);
const ci = ["1", "true"].includes(process.env.CI ?? "");
/** @type {CommandLineOptions} */
module.exports = minimist(process.argv.slice(2), {
const parsed = minimist(process.argv.slice(2), {
boolean: ["dirty", "light", "colors", "lkg", "soft", "fix", "failed", "keepFailed", "force", "built", "ci"],
string: ["browser", "tests", "break", "host", "reporter", "stackTraceLimit", "timeout", "shards", "shardId"],
alias: {
@@ -44,12 +42,19 @@ module.exports = minimist(process.argv.slice(2), {
}
});
if (module.exports.built) {
module.exports.lkg = false;
/** @type {CommandLineOptions} */
const options = /** @type {any} */ (parsed);
if (options.built) {
options.lkg = false;
}
export default options;
/**
* @typedef TypedOptions
* @typedef CommandLineOptions
* @property {boolean} dirty
* @property {boolean} light
* @property {boolean} colors
@@ -59,6 +64,7 @@ if (module.exports.built) {
* @property {boolean} fix
* @property {string} browser
* @property {string} tests
* @property {string | boolean} break
* @property {string | boolean} inspect
* @property {string} runners
* @property {string|number} workers
@@ -69,7 +75,7 @@ if (module.exports.built) {
* @property {boolean} failed
* @property {boolean} keepFailed
* @property {boolean} ci
*
* @typedef {import("minimist").ParsedArgs & TypedOptions} CommandLineOptions
* @property {string} shards
* @property {string} shardId
*/
void 0;
@@ -1,18 +1,17 @@
// @ts-check
const stream = require("stream");
const ts = require("../../lib/typescript");
const fs = require("fs");
const { base64VLQFormatEncode } = require("./sourcemaps");
import stream from "stream";
import ts from "../../lib/typescript.js";
import fs from "fs";
import { base64VLQFormatEncode } from "./sourcemaps.mjs";
/**
* @param {string | ((file: import("vinyl")) => string)} data
*/
function prepend(data) {
export function prepend(data) {
return new stream.Transform({
objectMode: true,
/**
* @param {string | Buffer | import("vinyl")} input
* @param {(error: Error, data?: any) => void} cb
* @param {(error: Error | null, data?: any) => void} cb
*/
transform(input, _, cb) {
if (typeof input === "string" || Buffer.isBuffer(input)) return cb(new Error("Only Vinyl files are supported."));
@@ -22,7 +21,7 @@ function prepend(data) {
const prependContent = typeof data === "function" ? data(input) : data;
output.contents = Buffer.concat([Buffer.from(prependContent, "utf8"), input.contents]);
if (input.sourceMap) {
if (typeof input.sourceMap === "string") input.sourceMap = /**@type {import("./sourcemaps").RawSourceMap}*/(JSON.parse(input.sourceMap));
if (typeof input.sourceMap === "string") input.sourceMap = /**@type {import("./sourcemaps.mjs").RawSourceMap}*/(JSON.parse(input.sourceMap));
const lineStarts = /**@type {*}*/(ts).computeLineStarts(prependContent);
let prependMappings = "";
for (let i = 1; i < lineStarts.length; i++) {
@@ -46,19 +45,17 @@ function prepend(data) {
return cb(null, output);
}
catch (e) {
return cb(e);
return cb(/** @type {Error} */(e));
}
}
});
}
exports.prepend = prepend;
/**
* @param {string | ((file: import("vinyl")) => string)} file
*/
function prependFile(file) {
export function prependFile(file) {
const data = typeof file === "string" ? fs.readFileSync(file, "utf8") :
vinyl => fs.readFileSync(file(vinyl), "utf8");
(/** @type {import("vinyl")} */ vinyl) => fs.readFileSync(file(vinyl), "utf8");
return prepend(data);
}
exports.prependFile = prependFile;
@@ -1,7 +1,7 @@
// @ts-check
const { exec, Debouncer } = require("./utils");
const { resolve } = require("path");
const { findUpRoot } = require("./findUpDir");
import { exec, Debouncer } from "./utils.mjs";
import { resolve } from "path";
import { findUpRoot } from "./findUpDir.mjs";
import assert from "assert";
class ProjectQueue {
/**
@@ -15,12 +15,13 @@ class ProjectQueue {
/**
* @param {string} project
* @param {object} options
* @param {{ lkg?: boolean; force?: boolean; }} options
*/
enqueue(project, { lkg = true, force = false } = {}) {
let entry = this._debouncers.find(entry => entry.lkg === lkg && entry.force === force);
if (!entry) {
const debouncer = new Debouncer(100, async () => {
assert(entry);
const projects = entry.projects;
if (projects) {
entry.projects = undefined;
@@ -49,14 +50,14 @@ const projectBuilder = new ProjectQueue((projects, lkg, force) => execTsc(lkg, .
* @param {boolean} [options.lkg=true]
* @param {boolean} [options.force=false]
*/
exports.buildProject = (project, { lkg, force } = {}) => projectBuilder.enqueue(project, { lkg, force });
export const buildProject = (project, { lkg, force } = {}) => projectBuilder.enqueue(project, { lkg, force });
const projectCleaner = new ProjectQueue((projects, lkg) => execTsc(lkg, "--clean", ...projects));
/**
* @param {string} project
*/
exports.cleanProject = (project) => projectCleaner.enqueue(project);
export const cleanProject = (project) => projectCleaner.enqueue(project);
const projectWatcher = new ProjectQueue((projects) => execTsc(/*lkg*/ true, "--watch", ...projects));
@@ -65,4 +66,4 @@ const projectWatcher = new ProjectQueue((projects) => execTsc(/*lkg*/ true, "--w
* @param {object} options
* @param {boolean} [options.lkg=true]
*/
exports.watchProject = (project, { lkg } = {}) => projectWatcher.enqueue(project, { lkg });
export const watchProject = (project, { lkg } = {}) => projectWatcher.enqueue(project, { lkg });
@@ -1,4 +1,3 @@
// @ts-check
/**
* @param {string} message
* @returns {never}
@@ -23,7 +22,7 @@ function base64FormatEncode(value) {
/**
* @param {number} value
*/
function base64VLQFormatEncode(value) {
export function base64VLQFormatEncode(value) {
if (value < 0) {
value = ((-value) << 1) + 1;
}
@@ -45,6 +44,5 @@ function base64VLQFormatEncode(value) {
return result;
}
exports.base64VLQFormatEncode = base64VLQFormatEncode;
/** @typedef {object} RawSourceMap */
@@ -1,28 +1,27 @@
// @ts-check
const del = require("del");
const fs = require("fs");
const os = require("os");
const path = require("path");
const mkdirP = require("mkdirp");
const log = require("fancy-log");
const cmdLineOptions = require("./options");
const { exec } = require("./utils");
const { findUpFile } = require("./findUpDir");
import del from "del";
import fs from "fs";
import os from "os";
import path from "path";
import mkdirP from "mkdirp";
import log from "fancy-log";
import cmdLineOptions from "./options.mjs";
import { exec } from "./utils.mjs";
import { findUpFile, findUpRoot } from "./findUpDir.mjs";
const mochaJs = require.resolve("mocha/bin/_mocha");
exports.localBaseline = "tests/baselines/local/";
exports.refBaseline = "tests/baselines/reference/";
exports.localRwcBaseline = "internal/baselines/rwc/local";
exports.refRwcBaseline = "internal/baselines/rwc/reference";
exports.localTest262Baseline = "internal/baselines/test262/local";
const mochaJs = path.resolve(findUpRoot(), "node_modules", "mocha", "bin", "_mocha");
export const localBaseline = "tests/baselines/local/";
export const refBaseline = "tests/baselines/reference/";
export const localRwcBaseline = "internal/baselines/rwc/local";
export const refRwcBaseline = "internal/baselines/rwc/reference";
export const localTest262Baseline = "internal/baselines/test262/local";
/**
* @param {string} runJs
* @param {string} defaultReporter
* @param {boolean} runInParallel
* @param {boolean} watchMode
* @param {boolean} _watchMode
*/
async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode) {
export async function runConsoleTests(runJs, defaultReporter, runInParallel, _watchMode) {
let testTimeout = cmdLineOptions.timeout;
const tests = cmdLineOptions.tests;
const inspect = cmdLineOptions.break || cmdLineOptions.inspect;
@@ -74,7 +73,7 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode)
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
if (!runInParallel) {
args.push(mochaJs);
args.push("-R", findUpFile("scripts/failed-tests.js"));
args.push("-R", findUpFile("scripts/failed-tests.cjs"));
args.push("-O", '"reporter=' + reporter + (keepFailed ? ",keepFailed=true" : "") + '"');
if (tests) {
args.push("-g", `"${tests}"`);
@@ -123,7 +122,7 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode)
errorStatus = exitCode;
error = new Error(`Process exited with status code ${errorStatus}.`);
}
else if (cmdLineOptions.ci) {
else if (cmdLineOptions.ci && runJs.startsWith("built")) {
// finally, do a sanity check and build the compiler with the built version of itself
log.info("Starting sanity check build...");
// Cleanup everything except lint rules (we'll need those later and would rather not waste time rebuilding them)
@@ -137,7 +136,7 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode)
}
catch (e) {
errorStatus = undefined;
error = e;
error = /** @type {Error} */ (e);
}
finally {
restoreSavedNodeEnv();
@@ -151,14 +150,12 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode)
throw error;
}
}
exports.runConsoleTests = runConsoleTests;
async function cleanTestDirs() {
await del([exports.localBaseline, exports.localRwcBaseline]);
mkdirP.sync(exports.localRwcBaseline);
mkdirP.sync(exports.localBaseline);
export async function cleanTestDirs() {
await del([localBaseline, localRwcBaseline]);
mkdirP.sync(localRwcBaseline);
mkdirP.sync(localBaseline);
}
exports.cleanTestDirs = cleanTestDirs;
/**
* used to pass data from gulp command line directly to run.js
@@ -173,7 +170,7 @@ exports.cleanTestDirs = cleanTestDirs;
* @param {number | undefined} [shards]
* @param {number | undefined} [shardId]
*/
function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
export function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, timeout, keepFailed, shards, shardId) {
const testConfigContents = JSON.stringify({
test: tests ? [tests] : undefined,
runners: runners ? runners.split(",") : undefined,
@@ -190,9 +187,8 @@ function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCou
log.info("Running tests with config: " + testConfigContents);
fs.writeFileSync("test.config", testConfigContents);
}
exports.writeTestConfigFile = writeTestConfigFile;
/** @type {string} */
/** @type {string | undefined} */
let savedNodeEnv;
function setNodeEnvToDevelopment() {
savedNodeEnv = process.env.NODE_ENV;
@@ -204,9 +200,12 @@ function restoreSavedNodeEnv() {
}
function deleteTemporaryProjectOutput() {
return del(path.join(exports.localBaseline, "projectOutput/"));
return del(path.join(localBaseline, "projectOutput/"));
}
/**
* @param {string} text
*/
function regExpEscape(text) {
return text.replace(/[.*+?^${}()|\[\]\\]/g, "\\$&");
}
@@ -1,20 +1,18 @@
// @ts-check
/* eslint-disable no-restricted-globals */
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../types/ambient.d.ts" />
const fs = require("fs");
const path = require("path");
const log = require("fancy-log");
const mkdirp = require("mkdirp");
const del = require("del");
const File = require("vinyl");
const ts = require("../../lib/typescript");
const chalk = require("chalk");
const which = require("which");
const { spawn } = require("child_process");
const { Readable, Duplex } = require("stream");
import fs from "fs";
import path from "path";
import log from "fancy-log";
import del from "del";
import File from "vinyl";
import ts from "../../lib/typescript.js";
import chalk from "chalk";
import which from "which";
import { spawn } from "child_process";
import { Duplex } from "stream";
import assert from "assert";
/**
* Executes the provided command once with the supplied arguments.
@@ -27,8 +25,8 @@ const { Readable, Duplex } = require("stream");
* @property {boolean} [hidePrompt]
* @property {boolean} [waitForExit=true]
*/
async function exec(cmd, args, options = {}) {
return /**@type {Promise<{exitCode: number}>}*/(new Promise((resolve, reject) => {
export async function exec(cmd, args, options = {}) {
return /**@type {Promise<{exitCode?: number}>}*/(new Promise((resolve, reject) => {
const { ignoreExitCode, waitForExit = true } = options;
if (!options.hidePrompt) log(`> ${chalk.green(cmd)} ${args.join(" ")}`);
@@ -36,7 +34,7 @@ async function exec(cmd, args, options = {}) {
if (waitForExit) {
proc.on("exit", exitCode => {
if (exitCode === 0 || ignoreExitCode) {
resolve({ exitCode });
resolve({ exitCode: exitCode ?? undefined });
}
else {
reject(new Error(`Process exited with code: ${exitCode}`));
@@ -53,7 +51,6 @@ async function exec(cmd, args, options = {}) {
}
}));
}
exports.exec = exec;
/**
* @param {ts.Diagnostic[]} diagnostics
@@ -64,7 +61,6 @@ function formatDiagnostics(diagnostics, options) {
? ts.formatDiagnosticsWithColorAndContext(diagnostics, getFormatDiagnosticsHost(options && options.cwd))
: ts.formatDiagnostics(diagnostics, getFormatDiagnosticsHost(options && options.cwd));
}
exports.formatDiagnostics = formatDiagnostics;
/**
* @param {ts.Diagnostic[]} diagnostics
@@ -73,7 +69,6 @@ exports.formatDiagnostics = formatDiagnostics;
function reportDiagnostics(diagnostics, options) {
log(formatDiagnostics(diagnostics, { cwd: options && options.cwd, pretty: process.stdout.isTTY }));
}
exports.reportDiagnostics = reportDiagnostics;
/**
* @param {string | undefined} cwd
@@ -82,17 +77,16 @@ exports.reportDiagnostics = reportDiagnostics;
function getFormatDiagnosticsHost(cwd) {
return {
getCanonicalFileName: fileName => fileName,
getCurrentDirectory: () => cwd,
getCurrentDirectory: () => cwd ?? process.cwd(),
getNewLine: () => ts.sys.newLine,
};
}
exports.getFormatDiagnosticsHost = getFormatDiagnosticsHost;
/**
* Reads JSON data with optional comments using the LKG TypeScript compiler
* @param {string} jsonPath
*/
function readJson(jsonPath) {
export function readJson(jsonPath) {
const jsonText = fs.readFileSync(jsonPath, "utf8");
const result = ts.parseConfigFileTextToJson(jsonPath, jsonText);
if (result.error) {
@@ -101,38 +95,13 @@ function readJson(jsonPath) {
}
return result.config;
}
exports.readJson = readJson;
/**
* @param {File} file
*/
function streamFromFile(file) {
return file.isBuffer() ? streamFromBuffer(file.contents) :
file.isStream() ? file.contents :
fs.createReadStream(file.path, { autoClose: true });
}
exports.streamFromFile = streamFromFile;
/**
* @param {Buffer} buffer
*/
function streamFromBuffer(buffer) {
return new Readable({
read() {
this.push(buffer);
// eslint-disable-next-line no-null/no-null
this.push(null);
}
});
}
exports.streamFromBuffer = streamFromBuffer;
/**
* @param {string | string[]} source
* @param {string | string[]} dest
* @returns {boolean}
*/
function needsUpdate(source, dest) {
export function needsUpdate(source, dest) {
if (typeof source === "string" && typeof dest === "string") {
if (fs.existsSync(dest)) {
const {mtime: outTime} = fs.statSync(dest);
@@ -194,9 +163,8 @@ function needsUpdate(source, dest) {
}
return true;
}
exports.needsUpdate = needsUpdate;
function getDiffTool() {
export function getDiffTool() {
const program = process.env.DIFF;
if (!program) {
log.warn("Add the 'DIFF' environment variable to the path of the program you want to use.");
@@ -204,7 +172,6 @@ function getDiffTool() {
}
return program;
}
exports.getDiffTool = getDiffTool;
/**
* Find the size of a directory recursively.
@@ -212,7 +179,7 @@ exports.getDiffTool = getDiffTool;
* @param {string} root
* @returns {number} bytes
*/
function getDirSize(root) {
export function getDirSize(root) {
const stats = fs.lstatSync(root);
if (!stats.isDirectory()) {
@@ -223,97 +190,12 @@ function getDirSize(root) {
.map(file => getDirSize(path.join(root, file)))
.reduce((acc, num) => acc + num, 0);
}
exports.getDirSize = getDirSize;
/**
* Flattens a project with project references into a single project.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {string} flattenedProjectSpec The output path for the flattened tsconfig.json file.
* @param {FlattenOptions} [options] Options used to flatten a project hierarchy.
*
* @typedef FlattenOptions
* @property {string} [cwd] The path to use for the current working directory. Defaults to `process.cwd()`.
* @property {import("../../lib/typescript").CompilerOptions} [compilerOptions] Compiler option overrides.
* @property {boolean} [force] Forces creation of the output project.
* @property {string[]} [exclude] Files to exclude (relative to `cwd`)
*/
function flatten(projectSpec, flattenedProjectSpec, options = {}) {
const cwd = normalizeSlashes(options.cwd ? path.resolve(options.cwd) : process.cwd());
const files = [];
const resolvedOutputSpec = path.resolve(cwd, flattenedProjectSpec);
const resolvedOutputDirectory = path.dirname(resolvedOutputSpec);
const resolvedProjectSpec = resolveProjectSpec(projectSpec, cwd, /*referrer*/ undefined);
const project = readJson(resolvedProjectSpec);
const skipProjects = /**@type {Set<string>}*/(new Set());
const skipFiles = new Set(options && options.exclude && options.exclude.map(file => normalizeSlashes(path.resolve(cwd, file))));
recur(resolvedProjectSpec, project);
if (options.force || needsUpdate(files, resolvedOutputSpec)) {
const config = {
extends: normalizeSlashes(path.relative(resolvedOutputDirectory, resolvedProjectSpec)),
compilerOptions: options.compilerOptions || {},
files: files.map(file => normalizeSlashes(path.relative(resolvedOutputDirectory, file)))
};
mkdirp.sync(resolvedOutputDirectory);
fs.writeFileSync(resolvedOutputSpec, JSON.stringify(config, undefined, 2), "utf8");
}
/**
* @param {string} projectSpec
* @param {object} project
*/
function recur(projectSpec, project) {
if (skipProjects.has(projectSpec)) return;
skipProjects.add(project);
if (project.references) {
for (const ref of project.references) {
const referencedSpec = resolveProjectSpec(ref.path, cwd, projectSpec);
const referencedProject = readJson(referencedSpec);
recur(referencedSpec, referencedProject);
}
}
if (project.include) {
throw new Error("Flattened project may not have an 'include' list.");
}
if (!project.files) {
throw new Error("Flattened project must have an explicit 'files' list.");
}
const projectDirectory = path.dirname(projectSpec);
for (let file of project.files) {
file = normalizeSlashes(path.resolve(projectDirectory, file));
if (skipFiles.has(file)) continue;
skipFiles.add(file);
files.push(file);
}
}
}
exports.flatten = flatten;
/**
* @param {string} file
*/
function normalizeSlashes(file) {
return file.replace(/\\/g, "/");
}
/**
* @param {string} projectSpec
* @param {string} cwd
* @param {string | undefined} referrer
* @returns {string}
*/
function resolveProjectSpec(projectSpec, cwd, referrer) {
const projectPath = normalizeSlashes(path.resolve(cwd, referrer ? path.dirname(referrer) : "", projectSpec));
const stats = fs.statSync(projectPath);
if (stats.isFile()) return normalizeSlashes(projectPath);
return normalizeSlashes(path.resolve(cwd, projectPath, "tsconfig.json"));
}
/**
* @param {string | ((file: File) => string) | { cwd?: string }} [dest]
* @param {{ cwd?: string }} [opts]
*/
function rm(dest, opts) {
export function rm(dest, opts) {
if (dest && typeof dest === "object") {
opts = dest;
dest = undefined;
@@ -328,7 +210,9 @@ function rm(dest, opts) {
const processDeleted = () => {
if (failed) return;
while (pending.length && pending[0].deleted) {
const { file, cb } = pending.shift();
const fileAndCallback = pending.shift();
assert(fileAndCallback);
const { file, cb } = fileAndCallback;
duplex.push(file);
cb();
}
@@ -382,7 +266,6 @@ function rm(dest, opts) {
});
return duplex;
}
exports.rm = rm;
class Deferred {
constructor() {
@@ -393,7 +276,7 @@ class Deferred {
}
}
class Debouncer {
export class Debouncer {
/**
* @param {number} timeout
* @param {() => Promise<any>} action
@@ -424,8 +307,8 @@ class Debouncer {
}
const deferred = this._deferred;
assert(deferred);
this._deferred = undefined;
this._projects = undefined;
try {
deferred.resolve(this._action());
}
@@ -434,4 +317,3 @@ class Debouncer {
}
}
}
exports.Debouncer = Debouncer;
@@ -1,25 +1,59 @@
/// <reference types="node"/>
import ts from "../lib/typescript.js";
import path from "path";
import assert from "assert";
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
/**
*
* @param {string} s
* @param {string} suffix
* @returns {boolean}
*/
function endsWith(s, suffix) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.length && declaration.members.every(m => !!m.initializer && m.initializer.kind === ts.SyntaxKind.StringLiteral);
/**
* @param {ts.EnumDeclaration} declaration
* @returns {boolean}
*/
function isStringEnum(declaration) {
return !!declaration.members.length && declaration.members.every(m => !!m.initializer && m.initializer.kind === ts.SyntaxKind.StringLiteral);
}
class DeclarationsWalker {
private visitedTypes: ts.Type[] = [];
private text = "";
private removedTypes: ts.Type[] = [];
/**
* @type {ts.Type[]}
* @private
*/
visitedTypes = [];
/**
* @type {string}
* @private
*/
text = "";
/**
* @type {ts.Type[]}
* @private
*/
removedTypes = [];
private constructor(private typeChecker: ts.TypeChecker, private protocolFile: ts.SourceFile) {
/**
* @param {ts.TypeChecker} typeChecker
* @param {ts.SourceFile} protocolFile
* @private
*/
constructor(typeChecker, protocolFile) {
this.typeChecker = typeChecker;
this.protocolFile = protocolFile;
}
static getExtraDeclarations(typeChecker: ts.TypeChecker, protocolFile: ts.SourceFile): string {
/**
*
* @param {ts.TypeChecker} typeChecker
* @param {ts.SourceFile} protocolFile
* @returns {string}
*/
static getExtraDeclarations(typeChecker, protocolFile) {
const walker = new DeclarationsWalker(typeChecker, protocolFile);
walker.visitTypeNodes(protocolFile);
let text = walker.text
@@ -36,7 +70,12 @@ class DeclarationsWalker {
return text;
}
private processType(type: ts.Type): void {
/**
* @param {ts.Type} type
* @returns {void}
* @private
*/
processType(type) {
if (this.visitedTypes.indexOf(type) >= 0) {
return;
}
@@ -47,7 +86,7 @@ class DeclarationsWalker {
}
if (s.name === "Array" || s.name === "ReadOnlyArray") {
// we should process type argument instead
return this.processType((type as any).typeArguments[0]);
return this.processType(/** @type {any} */(type).typeArguments[0]);
}
else {
const declarations = s.getDeclarations();
@@ -57,7 +96,7 @@ class DeclarationsWalker {
if (sourceFile === this.protocolFile || /lib(\..+)?\.d.ts/.test(path.basename(sourceFile.fileName))) {
return;
}
if (decl.kind === ts.SyntaxKind.EnumDeclaration && !isStringEnum(decl as ts.EnumDeclaration)) {
if (ts.isEnumDeclaration(decl) && !isStringEnum(decl)) {
this.removedTypes.push(type);
return;
}
@@ -74,7 +113,11 @@ class DeclarationsWalker {
}
}
private visitTypeNodes(node: ts.Node) {
/**
* @param {ts.Node} node
* @private
*/
visitTypeNodes(node) {
if (node.parent) {
switch (node.parent.kind) {
case ts.SyntaxKind.VariableDeclaration:
@@ -84,12 +127,13 @@ class DeclarationsWalker {
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.IndexSignature:
if (((node.parent as ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration).type) === node) {
const parent = /** @type {ts.VariableDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.ParameterDeclaration | ts.PropertySignature | ts.MethodSignature | ts.IndexSignatureDeclaration} */ (node.parent);
if (parent.type === node) {
this.processTypeOfNode(node);
}
break;
case ts.SyntaxKind.InterfaceDeclaration:
const heritageClauses = (node.parent as ts.InterfaceDeclaration).heritageClauses;
const heritageClauses = /** @type {ts.InterfaceDeclaration} */ (node.parent).heritageClauses;
if (heritageClauses) {
if (heritageClauses[0].token !== ts.SyntaxKind.ExtendsKeyword) {
throw new Error(`Unexpected kind of heritage clause: ${ts.SyntaxKind[heritageClauses[0].kind]}`);
@@ -104,9 +148,13 @@ class DeclarationsWalker {
ts.forEachChild(node, n => this.visitTypeNodes(n));
}
private processTypeOfNode(node: ts.Node): void {
/**
* @param {ts.Node} node
* @private
*/
processTypeOfNode(node) {
if (node.kind === ts.SyntaxKind.UnionType) {
for (const t of (node as ts.UnionTypeNode).types) {
for (const t of /** @type {ts.UnionTypeNode} */ (node).types) {
this.processTypeOfNode(t);
}
}
@@ -119,8 +167,14 @@ class DeclarationsWalker {
}
}
function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptServicesDts: string) {
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [] as string[], stripInternal: true };
/**
* @param {string} outputFile
* @param {string} protocolTs
* @param {string} typeScriptServicesDts
*/
function writeProtocolFile(outputFile, protocolTs, typeScriptServicesDts) {
/** @type {ts.CompilerOptions} */
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [], stripInternal: true };
/**
* 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped
@@ -129,7 +183,8 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
function getInitialDtsFileForProtocol() {
const program = ts.createProgram([protocolTs, typeScriptServicesDts, path.join(typeScriptServicesDts, "../lib.es5.d.ts")], options);
let protocolDts: string | undefined;
/** @type {string | undefined} */
let protocolDts;
const emitResult = program.emit(program.getSourceFile(protocolTs), (file, content) => {
if (endsWith(file, ".d.ts")) {
protocolDts = content;
@@ -137,7 +192,8 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
});
if (protocolDts === undefined) {
const diagHost: ts.FormatDiagnosticsHost = {
/** @type {ts.FormatDiagnosticsHost} */
const diagHost = {
getCanonicalFileName(f) { return f; },
getCurrentDirectory() { return "."; },
getNewLine() { return "\r\n"; }
@@ -151,12 +207,15 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
const protocolFileName = "protocol.d.ts";
/**
* Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts
* @param {string} protocolDts
* @param {boolean} includeTypeScriptServices
*/
function getProgramWithProtocolText(protocolDts: string, includeTypeScriptServices: boolean) {
function getProgramWithProtocolText(protocolDts, includeTypeScriptServices) {
const host = ts.createCompilerHost(options);
const originalGetSourceFile = host.getSourceFile;
host.getSourceFile = (fileName) => {
if (fileName === protocolFileName) {
assert(options.target !== undefined);
return ts.createSourceFile(fileName, protocolDts, options.target);
}
return originalGetSourceFile.apply(host, [fileName, ts.ScriptTarget.Latest]);
@@ -168,7 +227,8 @@ function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptSer
let protocolDts = getInitialDtsFileForProtocol();
const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true);
const protocolFile = program.getSourceFile("protocol.d.ts")!;
const protocolFile = program.getSourceFile("protocol.d.ts");
assert(protocolFile);
const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile);
if (extraDeclarations) {
protocolDts += extraDeclarations;
-87
View File
@@ -1,87 +0,0 @@
/// <reference types="node"/>
import { normalize, dirname, join } from "path";
import { readFileSync, writeFileSync, unlinkSync, existsSync } from "fs";
import * as assert from "assert";
import { execSync } from "child_process";
const args = process.argv.slice(2);
/**
* A minimal description for a parsed package.json object.
*/
interface PackageJson {
name: string;
bin?: {};
main: string;
scripts: {
prepare?: string
postpublish?: string
}
}
function main(): void {
if (args.length < 1) {
console.log("Usage:");
console.log("\tnode configureTSCBuild.js <package.json location>");
return;
}
// Acquire the version from the package.json file and modify it appropriately.
const packageJsonFilePath = normalize(args[0]);
const packageJsonValue: PackageJson = JSON.parse(readFileSync(packageJsonFilePath).toString());
// Remove the bin section from the current package
delete packageJsonValue.bin;
// We won't be running eslint which would run before publishing
delete packageJsonValue.scripts.prepare;
// No infinite loops
delete packageJsonValue.scripts.postpublish;
// Set the new name
packageJsonValue.name = "@typescript/language-services";
writeFileSync(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4));
// Remove the files which aren't use when just using the API
const toRemove = [
// JS Files
"tsserver.js",
"tsserverlibrary.js",
"typescriptServices.js",
"typingsInstaller.js",
"tsc.js",
// DTS files
"typescriptServices.d.ts",
"tsserverlibrary.d.ts"
];
// Get a link to the main dependency JS file
const lib = join(dirname(packageJsonFilePath), packageJsonValue.main);
const libPath = dirname(lib);
// Remove the sibling JS large files referenced above
toRemove.forEach(file => {
const path = join(libPath, file);
if (existsSync(path)) unlinkSync(path);
});
// Remove VS-specific localization keys
execSync("rm -rf loc", { cwd: dirname(packageJsonFilePath) });
// Remove runnable file reference
execSync("rm -rf bin", { cwd: dirname(packageJsonFilePath) });
///////////////////////////////////
// This section verifies that the build of TypeScript compiles and emits
const ts = require(lib);
const source = "let x: string = 'string'";
const results = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.CommonJS }
});
assert(results.outputText.trim() === "var x = 'string';", `Running typescript with ${packageJsonValue.name} did not return the expected results, got: ${results.outputText}`);
}
main();
@@ -1,18 +1,20 @@
/// <reference types="node"/>
import { normalize, relative } from "path";
import * as assert from "assert";
import assert from "assert";
import { readFileSync, writeFileSync } from "fs";
import url from "url";
const __filename = url.fileURLToPath(new URL(import.meta.url));
/**
* A minimal description for a parsed package.json object.
*/
interface PackageJson {
* @typedef {{
name: string;
version: string;
keywords: string[];
}
}} PackageJson
*/
function main(): void {
function main() {
const args = process.argv.slice(2);
if (args.length < 3) {
const thisProgramName = relative(process.cwd(), __filename);
@@ -28,7 +30,8 @@ function main(): void {
// Acquire the version from the package.json file and modify it appropriately.
const packageJsonFilePath = normalize(args[1]);
const packageJsonValue: PackageJson = JSON.parse(readFileSync(packageJsonFilePath).toString());
/** @type {PackageJson} */
const packageJsonValue = JSON.parse(readFileSync(packageJsonFilePath).toString());
const { majorMinor, patch } = parsePackageJsonVersion(packageJsonValue.version);
const prereleasePatch = getPrereleasePatch(tag, patch);
@@ -53,17 +56,25 @@ function main(): void {
}
/* eslint-disable no-null/no-null */
function updateTsFile(tsFilePath: string, tsFileContents: string, majorMinor: string, patch: string, nightlyPatch: string): string {
/**
* @param {string} tsFilePath
* @param {string} tsFileContents
* @param {string} majorMinor
* @param {string} patch
* @param {string} nightlyPatch
* @returns {string}
*/
function updateTsFile(tsFilePath, tsFileContents, majorMinor, patch, nightlyPatch) {
const majorMinorRgx = /export const versionMajorMinor = "(\d+\.\d+)"/;
const majorMinorMatch = majorMinorRgx.exec(tsFileContents);
assert(majorMinorMatch !== null, `The file '${tsFilePath}' seems to no longer have a string matching '${majorMinorRgx}'.`);
const parsedMajorMinor = majorMinorMatch![1];
const parsedMajorMinor = majorMinorMatch[1];
assert(parsedMajorMinor === majorMinor, `versionMajorMinor does not match. ${tsFilePath}: '${parsedMajorMinor}'; package.json: '${majorMinor}'`);
const versionRgx = /export const version(?:: string)? = `\$\{versionMajorMinor\}\.(\d)(-\w+)?`;/;
const patchMatch = versionRgx.exec(tsFileContents);
assert(patchMatch !== null, `The file '${tsFilePath}' seems to no longer have a string matching '${versionRgx.toString()}'.`);
const parsedPatch = patchMatch![1];
const parsedPatch = patchMatch[1];
if (parsedPatch !== patch) {
throw new Error(`patch does not match. ${tsFilePath}: '${parsedPatch}; package.json: '${patch}'`);
}
@@ -71,16 +82,25 @@ function updateTsFile(tsFilePath: string, tsFileContents: string, majorMinor: st
return tsFileContents.replace(versionRgx, `export const version: string = \`\${versionMajorMinor}.${nightlyPatch}\`;`);
}
function parsePackageJsonVersion(versionString: string): { majorMinor: string, patch: string } {
/**
* @param {string} versionString
* @returns {{ majorMinor: string, patch: string }}
*/
function parsePackageJsonVersion(versionString) {
const versionRgx = /(\d+\.\d+)\.(\d+)($|\-)/;
const match = versionString.match(versionRgx);
assert(match !== null, "package.json 'version' should match " + versionRgx.toString());
return { majorMinor: match![1], patch: match![2] };
return { majorMinor: match[1], patch: match[2] };
}
/* eslint-enable no-null/no-null */
/** e.g. 0-dev.20170707 */
function getPrereleasePatch(tag: string, plainPatch: string): string {
/**
* e.g. 0-dev.20170707
* @param {string} tag
* @param {string} plainPatch
* @returns {string}
*/
function getPrereleasePatch(tag, plainPatch) {
// We're going to append a representation of the current time at the end of the current version.
// String.prototype.toISOString() returns a 24-character string formatted as 'YYYY-MM-DDTHH:mm:ss.sssZ',
// but we'd prefer to just remove separators and limit ourselves to YYYYMMDD.
-313
View File
@@ -1,313 +0,0 @@
/* eslint-disable */
// @ts-check
/** Run via:
node scripts/createPlaygroundBuild.js
*/
// This script does two things:
//
// - Listens to changes to the built version of TypeScript (via a filewatcher on `built/local/typescriptServices.js`)
// these trigger creating monaco-typescript compatible builds of TypeScript at `internal/lib/typescriptServices.js§
//
// - Creates a HTTP server which the playground uses. The webserver almost exclusively re-directs requests to
// the latest stable version of monaco-typescript, but specifically overrides requests for the TypeScript js
// file to the version created in the above step.
//
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const path = require('path');
const fs = require('fs');
const child_process = require('child_process');
const http = require('http');
const url = require('url');
const nodeFetch = require("node-fetch").default
function updateTSDist() {
// This code is a direct port of a script from monaco-typescript
// https://github.com/microsoft/monaco-typescript/blob/master/scripts/importTypescript.js
// Currently based on cc8da6b on June 6 2021
const generatedNote = `//
// **NOTE**: Do not edit directly! This file is generated using \`npm run import-typescript\`
//
`;
const TYPESCRIPT_LIB_SOURCE = path.join(__dirname, '../built/local');
const TYPESCRIPT_LIB_DESTINATION = path.join(__dirname, '../internal/lib');
(function () {
try {
fs.statSync(TYPESCRIPT_LIB_DESTINATION);
} catch (err) {
fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION);
}
importLibs();
const npmLsOutput = JSON.parse(
child_process.execSync('npm ls typescript --depth=0 --json=true').toString()
);
const typeScriptDependencyVersion = npmLsOutput.version;
fs.writeFileSync(
path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServicesMetadata.ts'),
`${generatedNote}
export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
);
let tsServices = fs
.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js'))
.toString();
// Ensure we never run into the node system...
// (this also removes require calls that trick webpack into shimming those modules...)
tsServices = tsServices.replace(
/\n ts\.sys =([^]*)\n \}\)\(\);/m,
`\n // MONACOCHANGE\n ts.sys = undefined;\n // END MONACOCHANGE`
);
// Eliminate more require() calls...
tsServices = tsServices.replace(
/^( +)etwModule = require\(.*$/m,
'$1// MONACOCHANGE\n$1etwModule = undefined;\n$1// END MONACOCHANGE'
);
tsServices = tsServices.replace(
/^( +)var result = ts\.sys\.require\(.*$/m,
'$1// MONACOCHANGE\n$1var result = undefined;\n$1// END MONACOCHANGE'
);
tsServices = tsServices.replace(
/^( +)fs = require\("fs"\);$/m,
'$1// MONACOCHANGE\n$1fs = undefined;\n$1// END MONACOCHANGE'
);
tsServices = tsServices.replace(
/^( +)debugger;$/m,
'$1// MONACOCHANGE\n$1// debugger;\n$1// END MONACOCHANGE'
);
tsServices = tsServices.replace(
/= require\("perf_hooks"\)/m,
'/* MONACOCHANGE */= {}/* END MONACOCHANGE */'
);
// Flag any new require calls (outside comments) so they can be corrected preemptively.
// To avoid missing cases (or using an even more complex regex), temporarily remove comments
// about require() and then check for lines actually calling require().
// \/[*/] matches the start of a comment (single or multi-line).
// ^\s+\*[^/] matches (presumably) a later line of a multi-line comment.
const tsServicesNoCommentedRequire = tsServices.replace(
/(\/[*/]|^\s+\*[^/]).*\brequire\(.*/gm,
''
);
const linesWithRequire = tsServicesNoCommentedRequire.match(/^.*?\brequire\(.*$/gm);
// Allow error messages to include references to require() in their strings
const runtimeRequires =
linesWithRequire &&
linesWithRequire.filter((l) => !l.includes(': diag(') && !l.includes('ts.DiagnosticCategory'));
if (runtimeRequires && runtimeRequires.length && linesWithRequire) {
console.error(
'Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n'
);
console.error(
runtimeRequires.map((r) => `${r} (${tsServicesNoCommentedRequire.indexOf(r)})`).join('\n')
);
process.exit(1);
}
const tsServices_amd =
generatedNote +
tsServices +
`
// MONACOCHANGE
// Defining the entire module name because r.js has an issue and cannot bundle this file
// correctly with an anonymous define call
define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
// END MONACOCHANGE
`;
fs.writeFileSync(
path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices-amd.js'),
stripSourceMaps(tsServices_amd)
);
const tsServices_esm =
generatedNote +
tsServices +
`
// MONACOCHANGE
export var createClassifier = ts.createClassifier;
export var createLanguageService = ts.createLanguageService;
export var displayPartsToString = ts.displayPartsToString;
export var EndOfLineState = ts.EndOfLineState;
export var flattenDiagnosticMessageText = ts.flattenDiagnosticMessageText;
export var IndentStyle = ts.IndentStyle;
export var ScriptKind = ts.ScriptKind;
export var ScriptTarget = ts.ScriptTarget;
export var TokenClass = ts.TokenClass;
// END MONACOCHANGE
`;
fs.writeFileSync(
path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'),
stripSourceMaps(tsServices_esm)
);
let dtsServices = fs
.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts'))
.toString();
dtsServices += `
// MONACOCHANGE
export = ts;
// END MONACOCHANGE
`;
fs.writeFileSync(
path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'),
generatedNote + dtsServices
);
})();
function importLibs() {
function readLibFile(name) {
const srcPath = path.join(TYPESCRIPT_LIB_SOURCE, name);
return fs.readFileSync(srcPath).toString();
}
let strLibResult = `/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
${generatedNote}
/** Contains all the lib files */
export const libFileMap: Record<string, string> = {}
`;
let strIndexResult = `/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
${generatedNote}
/** Contains all the lib files */
export const libFileSet: Record<string, boolean> = {}
`;
const dtsFiles = fs.readdirSync(TYPESCRIPT_LIB_SOURCE).filter((f) => f.includes('lib.'));
while (dtsFiles.length > 0) {
const name = dtsFiles.shift();
const output = readLibFile(name).replace(/\r\n/g, '\n');
strLibResult += `libFileMap['${name}'] = "${escapeText(output)}";\n`;
strIndexResult += `libFileSet['${name}'] = true;\n`;
}
fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts'), strLibResult);
fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.index.ts'), strIndexResult);
}
/**
* Escape text such that it can be used in a javascript string enclosed by double quotes (")
*/
function escapeText(text) {
// See http://www.javascriptkit.com/jsref/escapesequence.shtml
const _backspace = '\b'.charCodeAt(0);
const _formFeed = '\f'.charCodeAt(0);
const _newLine = '\n'.charCodeAt(0);
const _nullChar = 0;
const _carriageReturn = '\r'.charCodeAt(0);
const _tab = '\t'.charCodeAt(0);
const _verticalTab = '\v'.charCodeAt(0);
const _backslash = '\\'.charCodeAt(0);
const _doubleQuote = '"'.charCodeAt(0);
const len = text.length;
let startPos = 0;
let chrCode;
let replaceWith = null;
let resultPieces = [];
for (let i = 0; i < len; i++) {
chrCode = text.charCodeAt(i);
switch (chrCode) {
case _backspace:
replaceWith = '\\b';
break;
case _formFeed:
replaceWith = '\\f';
break;
case _newLine:
replaceWith = '\\n';
break;
case _nullChar:
replaceWith = '\\0';
break;
case _carriageReturn:
replaceWith = '\\r';
break;
case _tab:
replaceWith = '\\t';
break;
case _verticalTab:
replaceWith = '\\v';
break;
case _backslash:
replaceWith = '\\\\';
break;
case _doubleQuote:
replaceWith = '\\"';
break;
}
if (replaceWith !== null) {
resultPieces.push(text.substring(startPos, i));
resultPieces.push(replaceWith);
startPos = i + 1;
replaceWith = null;
}
}
resultPieces.push(text.substring(startPos, len));
return resultPieces.join('');
}
function stripSourceMaps(str) {
return str.replace(/\/\/# sourceMappingURL[^\n]+/gm, '');
}
/// End of import
}
const services = path.join(__dirname, '../built/local/typescriptServices.js');
fs.watchFile(services, () =>{
console.log("Updating the monaco build")
updateTSDist()
})
// We need to re-direct non TSC JS requests back to a real copy of
// monaco, so grab the list of official releases from the TS CDN
// and use the latest stable release, as that is most likely the
// closest version to your dev build
let latestStable = "4.3.2"
nodeFetch('https://typescript.azureedge.net/indexes/releases.json').then(req => req.json()).then(releases => {
latestStable = releases.versions.pop()
});
http.createServer(function (req, res) {
res.setHeader("Access-Control-Allow-Origin", "*")
const incoming = url.parse(req.url)
if (incoming.path.endsWith("typescriptServices.js")) {
// Use the built version
res.writeHead(200, {"Content-Type": "text/javascript"});
const amdPath = path.join(__dirname, '../internal/lib/typescriptServices-amd.js');
res.write(fs.readFileSync(amdPath))
} else {
// Redirect to the TS CDN
res.writeHead(302, {
'Location': `https://typescript.azureedge.net/cdn/${latestStable}/monaco${incoming.path}`
});
}
res.end();
}).listen(5615);
console.log("Starting servers\n")
console.log(" - [✓] file watcher: " + services)
updateTSDist()
console.log(" - [✓] http server: http://localhost:5615")
console.log("\n\nGet started: http://www.staging-typescript.org/play?ts=dev")
@@ -1,7 +1,7 @@
import * as fs from "fs";
import * as fsPromises from "fs/promises";
import * as _glob from "glob";
import * as util from "util";
import fs from "fs";
import fsPromises from "fs/promises";
import _glob from "glob";
import util from "util";
const glob = util.promisify(_glob);
@@ -24,7 +24,7 @@ async function checkErrorBaselines() {
fs.readFile(baseDir + f, "utf-8", (err, baseline) => {
if (err) throw err;
let g: RegExpExecArray | null;
let g;
while (g = errRegex.exec(baseline)) {
const errCode = +g[1];
const msg = keys.filter(k => messages[k].code === errCode)[0];
@@ -48,8 +48,8 @@ async function checkSourceFiles() {
const data = await fsPromises.readFile("src/compiler/diagnosticInformationMap.generated.ts", "utf-8");
const errorRegexp = /\s(\w+): \{ code/g;
const errorNames: string[] = [];
let errMatch: RegExpExecArray | null;
const errorNames = [];
let errMatch;
while (errMatch = errorRegexp.exec(data)) {
errorNames.push(errMatch[1]);
}
@@ -1,5 +1,5 @@
const { AST_NODE_TYPES, TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "boolean-trivia",
@@ -1,5 +1,5 @@
const { AST_NODE_TYPES, TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "debug-assert",
@@ -1,5 +1,5 @@
const { TSESTree, AST_NODE_TYPES } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "no-double-space",
@@ -1,5 +1,5 @@
const { TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "no-in-operator",
@@ -1,5 +1,5 @@
const { TSESTree, AST_NODE_TYPES } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "no-keywords",
@@ -1,5 +1,5 @@
const { TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "no-type-assertion-whitespace",
@@ -1,5 +1,5 @@
const { TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "object-literal-surrounding-space",
@@ -1,5 +1,5 @@
const { AST_NODE_TYPES, TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "one-namespace-per-file",
@@ -1,5 +1,5 @@
const { AST_NODE_TYPES, TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "only-arrow-functions",
@@ -1,5 +1,5 @@
const { TSESTree } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "simple-indent",
@@ -1,5 +1,5 @@
const { TSESTree, AST_TOKEN_TYPES } = require("@typescript-eslint/utils");
const { createRule } = require("./utils");
const { createRule } = require("./utils.cjs");
module.exports = createRule({
name: "type-operator-spacing",
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/boolean-trivia");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/boolean-trivia.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/debug-assert");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/debug-assert.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/no-double-space");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/no-double-space.cjs");
const ruleTester = new RuleTester({
parser: require.resolve("@typescript-eslint/parser"),
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/no-in-operator");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/no-in-operator.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/no-keywords");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/no-keywords.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/no-type-assertion-whitespace");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/no-type-assertion-whitespace.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/object-literal-surrounding-space");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/object-literal-surrounding-space.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/only-arrow-functions");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/only-arrow-functions.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/simple-indent");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/simple-indent.cjs");
const ruleTester = new RuleTester({
parserOptions: {
@@ -0,0 +1,6 @@
const path = require("path");
const { TSESLint } = require("@typescript-eslint/utils");
module.exports.ROOT_DIR = path.join(process.cwd(), "scripts", "eslint", "tests", "fixtures");
module.exports.FILENAME = path.join(module.exports.ROOT_DIR, "file.ts");
module.exports.RuleTester = TSESLint.RuleTester;
@@ -1,6 +0,0 @@
import * as path from "path";
import { TSESLint } from "@typescript-eslint/utils";
export const ROOT_DIR = path.join(process.cwd(), "scripts", "eslint", "tests", "fixtures");
export const FILENAME = path.join(ROOT_DIR, "file.ts");
export const RuleTester = TSESLint.RuleTester;
@@ -1,5 +1,5 @@
import { RuleTester } from "./support/RuleTester";
import rule = require("../rules/type-operator-spacing");
const { RuleTester } = require("./support/RuleTester.cjs");
const rule = require("../rules/type-operator-spacing.cjs");
const ruleTester = new RuleTester({
parserOptions: {
-30
View File
@@ -1,30 +0,0 @@
{
"compilerOptions": {
"lib": [
"es6"
],
"module": "commonjs",
"target": "es6",
"outDir": "./built",
"declaration": false,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"allowUnusedLabels": false,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowJs": true,
"checkJs": true
},
"include": [
"rules",
"tests"
]
}
@@ -1,15 +1,19 @@
// @ts-check
const assert = require("assert");
const Mocha = require("mocha");
const path = require("path");
const fs = require("fs");
const os = require("os");
const failingHookRegExp = /^(.*) "(before|after) (all|each)" hook$/;
/** @typedef {{
file?: string;
keepFailed?: boolean;
reporter?: Mocha.ReporterConstructor | keyof Mocha.reporters;
reporterOptions?: any; // TODO(jakebailey): what?
}} ReporterOptions */
/**
* .failed-tests reporter
*
* @typedef {Object} ReporterOptions
* @property {string} [file]
* @property {boolean} [keepFailed]
* @property {string|Mocha.ReporterConstructor} [reporter]
@@ -24,7 +28,7 @@ class FailedTestsReporter extends Mocha.reporters.Base {
super(runner, options);
if (!runner) return;
const reporterOptions = this.reporterOptions = options.reporterOptions || {};
const reporterOptions = this.reporterOptions = options?.reporterOptions || {};
if (reporterOptions.file === undefined) reporterOptions.file = ".failed-tests";
if (reporterOptions.keepFailed === undefined) reporterOptions.keepFailed = false;
if (reporterOptions.reporter) {
@@ -67,7 +71,7 @@ class FailedTestsReporter extends Mocha.reporters.Base {
* @param {ReadonlyArray<Mocha.Test>} passes
* @param {ReadonlyArray<Mocha.Test | Mocha.Hook>} failures
* @param {boolean} keepFailed
* @param {(err?: NodeJS.ErrnoException) => void} done
* @param {(err?: NodeJS.ErrnoException | null) => void} done
*/
static writeFailures(file, passes, failures, keepFailed, done) {
const failingTests = new Set(fs.existsSync(file) ? readTests() : undefined);
@@ -78,6 +82,7 @@ class FailedTestsReporter extends Mocha.reporters.Base {
if (failingTests.size > 0 && !keepFailed) {
for (const test of passes) {
failingTests.delete(test.fullTitle().trim());
assert(test.parent);
possiblyPassingSuites.add(test.parent.fullTitle().trim());
}
}
@@ -86,6 +91,7 @@ class FailedTestsReporter extends Mocha.reporters.Base {
// containing suite as failing. If the suite for a test or hook was
// possibly passing then it is now definitely failing.
for (const test of failures) {
assert(test.parent);
const suiteTitle = test.parent.fullTitle().trim();
if (test.type === "test") {
failingTests.add(test.fullTitle().trim());
@@ -126,8 +132,11 @@ class FailedTestsReporter extends Mocha.reporters.Base {
/**
* @param {number} failures
* @param {(failures: number) => void} [fn]
* @override
*/
done(failures, fn) {
assert(this.reporterOptions);
assert(this.reporterOptions.file);
FailedTestsReporter.writeFailures(this.reporterOptions.file, this.passes, this.failures, this.reporterOptions.keepFailed || this.stats.tests === 0, (err) => {
const reporter = this.reporter;
if (reporter && reporter.done) {
+52
View File
@@ -0,0 +1,52 @@
export = FailedTestsReporter;
/** @typedef {{
file?: string;
keepFailed?: boolean;
reporter?: Mocha.ReporterConstructor | keyof Mocha.reporters;
reporterOptions?: any; // TODO(jakebailey): what?
}} ReporterOptions */
/**
* .failed-tests reporter
*
* @property {string} [file]
* @property {boolean} [keepFailed]
* @property {string|Mocha.ReporterConstructor} [reporter]
* @property {*} [reporterOptions]
*/
declare class FailedTestsReporter extends Mocha.reporters.Base {
/**
* @param {string} file
* @param {ReadonlyArray<Mocha.Test>} passes
* @param {ReadonlyArray<Mocha.Test | Mocha.Hook>} failures
* @param {boolean} keepFailed
* @param {(err?: NodeJS.ErrnoException | null) => void} done
*/
static writeFailures(file: string, passes: ReadonlyArray<Mocha.Test>, failures: ReadonlyArray<Mocha.Test | Mocha.Hook>, keepFailed: boolean, done: (err?: NodeJS.ErrnoException | null) => void): void;
/**
* @param {Mocha.Runner} runner
* @param {{ reporterOptions?: ReporterOptions }} [options]
*/
constructor(runner: Mocha.Runner, options?: {
reporterOptions?: ReporterOptions | undefined;
} | undefined);
reporterOptions: ReporterOptions | undefined;
reporter: Mocha.reporters.Base | undefined;
/** @type {Mocha.Test[]} */
passes: Mocha.Test[];
/**
* @param {number} failures
* @param {(failures: number) => void} [fn]
* @override
*/
override done(failures: number, fn?: ((failures: number) => void) | undefined): void;
}
declare namespace FailedTestsReporter {
export { ReporterOptions };
}
import Mocha = require("mocha");
type ReporterOptions = {
file?: string;
keepFailed?: boolean;
reporter?: Mocha.ReporterConstructor | keyof typeof Mocha.reporters;
reporterOptions?: any;
};
-22
View File
@@ -1,22 +0,0 @@
import * as Mocha from "mocha";
export = FailedTestsReporter;
declare class FailedTestsReporter extends Mocha.reporters.Base {
passes: Mocha.Test[];
failures: Mocha.Test[];
reporterOptions: FailedTestsReporter.ReporterOptions;
reporter?: Mocha.reporters.Base;
constructor(runner: Mocha.Runner, options?: { reporterOptions?: FailedTestsReporter.ReporterOptions });
static writeFailures(file: string, passes: readonly Mocha.Test[], failures: readonly Mocha.Test[], keepFailed: boolean, done: (err?: NodeJS.ErrnoException) => void): void;
done(failures: number, fn?: (failures: number) => void): void;
}
declare namespace FailedTestsReporter {
interface ReporterOptions {
file?: string;
keepFailed?: boolean;
reporter?: string | Mocha.ReporterConstructor;
reporterOptions?: any;
}
}
+2 -2
View File
@@ -1,14 +1,14 @@
// @ts-check
// This file requires a modern version of node 14+, and grep to be available.
// node scripts/find-unused-diagnostic-messages.mjs
import { readFileSync } from "fs";
import {EOL} from "os";
import { EOL } from "os";
import { execSync } from "child_process";
const diags = readFileSync("src/compiler/diagnosticInformationMap.generated.ts", "utf8");
const startOfDiags = diags.split("export const Diagnostics")[1];
/** @type {string[]} */
const missingNames = [];
startOfDiags.split(EOL).forEach(line => {
if (!line.includes(":")) return;
@@ -1,8 +1,8 @@
import * as fs from "fs";
import * as path from "path";
import * as xml2js from "xml2js";
import fs from "fs";
import path from "path";
import xml2js from "xml2js";
function main(): void {
function main() {
const args = process.argv.slice(2);
if (args.length !== 3) {
console.log("Usage:");
@@ -25,7 +25,10 @@ function main(): void {
return;
function visitDirectory(name: string) {
/**
* @param {string} name
*/
function visitDirectory(name) {
const inputFilePath = path.join(inputPath, name, "diagnosticMessages", "diagnosticMessages.generated.json.lcl");
fs.readFile(inputFilePath, (err, data) => {
@@ -63,8 +66,10 @@ function main(): void {
*
* Most of the languages we support are neutral locales, so we want to use the language name.
* There are three exceptions, zh-CN, zh-TW and pt-BR.
*
* @param {string} localeName
*/
function getPreferredLocaleName(localeName: string) {
function getPreferredLocaleName(localeName) {
switch (localeName) {
case "zh-CN":
case "zh-TW":
@@ -75,15 +80,22 @@ function main(): void {
}
}
function handleError(err: null | object) {
/**
* @param {null | object} err
*/
function handleError(err) {
if (err) {
console.error(err);
process.exit(1);
}
}
function xmlObjectToString(o: any) {
const out: any = {};
/**
* @param {any} o
*/
function xmlObjectToString(o) {
/** @type {any} */
const out = {};
for (const item of o.LCX.Item[0].Item[0].Item) {
let ItemId = item.$.ItemId;
let val = item.Str[0].Tgt ? item.Str[0].Tgt[0].Val[0] : item.Str[0].Val[0];
@@ -104,7 +116,11 @@ function main(): void {
}
function ensureDirectoryExists(directoryPath: string, action: () => void) {
/**
* @param {string} directoryPath
* @param {() => void} action
*/
function ensureDirectoryExists(directoryPath, action) {
fs.exists(directoryPath, exists => {
if (!exists) {
const basePath = path.dirname(directoryPath);
@@ -116,14 +132,21 @@ function main(): void {
});
}
function writeFile(fileName: string, contents: string) {
/**
* @param {string} fileName
* @param {string} contents
*/
function writeFile(fileName, contents) {
ensureDirectoryExists(path.dirname(fileName), () => {
fs.writeFile(fileName, contents, handleError);
});
}
function objectToList(o: Record<string, string>) {
const list: { key: string, value: string }[] = [];
/**
* @param {Record<string, string>} o
*/
function objectToList(o) {
const list = [];
for (const key in o) {
list.push({ key, value: o[key] });
}
@@ -142,9 +165,13 @@ function main(): void {
));
});
function getItemXML(key: string, value: string) {
/**
* @param {string} key
* @param {string} value
*/
function getItemXML(key, value) {
// escape entrt value
value = value.replace(/]/, "]5D;");
value = value.replace(/]/g, "]5D;");
return `
<Item ItemId=";${key}" ItemType="0" PsrId="306" Leaf="true">
@@ -155,7 +182,10 @@ function main(): void {
</Item>`;
}
function getLCGFileXML(items: string) {
/**
* @param {string} items
*/
function getLCGFileXML(items) {
return `<?xml version="1.0" encoding="utf-8"?>
<LCX SchemaVersion="6.0" Name="diagnosticMessages.generated.json" PsrId="306" FileType="1" SrcCul="en-US" xmlns="http://schemas.microsoft.com/locstudio/2006/6/lcx">
<OwnedComments>
@@ -1,17 +1,11 @@
import * as fs from "fs";
import * as path from "path";
import * as os from "os";
import * as childProcess from "child_process";
import url from "url";
interface Map<T> {
[key: string]: T;
}
declare let process: {
argv: string[];
env: Map<string>;
exit(exitCode?: number): void;
};
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
main();
function main() {
@@ -35,25 +29,41 @@ function main() {
importDefinitelyTypedTests(tscPath, rwcTestPath, resolvedDefinitelyTypedRoot);
}
function filePathEndsWith(path: string, endingString: string): boolean {
/**
* @param {string} path
* @param {string} endingString
* @returns {boolean}
*/
function filePathEndsWith(path, endingString) {
const pathLen = path.length;
const extLen = endingString.length;
return pathLen > extLen && path.substr(pathLen - extLen, extLen).toLocaleLowerCase() === endingString.toLocaleLowerCase();
}
function copyFileSync(source: string, destination: string) {
/**
* @param {string} source
* @param {string} destination
*/
function copyFileSync(source, destination) {
const text = fs.readFileSync(source);
fs.writeFileSync(destination, text);
}
function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCaseName: string, testFiles: string[], responseFile: string | undefined) {
/**
* @param {string} tscPath
* @param {string} rwcTestPath
* @param {string} testCaseName
* @param {string[]} testFiles
* @param {string | undefined} responseFile
*/
function importDefinitelyTypedTest(tscPath, rwcTestPath, testCaseName, testFiles, responseFile) {
let cmd = "node " + tscPath + " --module commonjs " + testFiles.join(" ");
if (responseFile) {
cmd += " @" + responseFile;
}
const testDirectoryName = testCaseName + "_" + Math.floor((Math.random() * 10000) + 1);
const testDirectoryPath = path.join(process.env.temp, testDirectoryName);
const testDirectoryPath = path.join(os.tmpdir(), testDirectoryName);
if (fs.existsSync(testDirectoryPath)) {
throw new Error("Could not create test directory");
}
@@ -94,13 +104,18 @@ function importDefinitelyTypedTest(tscPath: string, rwcTestPath: string, testCas
}
//console.log("\r\n");
}).on("error", (error: any) => {
}).on("error", (error) => {
console.log("==> error " + JSON.stringify(error));
console.log("\r\n");
});
}
function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, definitelyTypedRoot: string): void {
/**
* @param {string} tscPath
* @param {string} rwcTestPath
* @param {string} definitelyTypedRoot
*/
function importDefinitelyTypedTests(tscPath, rwcTestPath, definitelyTypedRoot) {
fs.readdir(definitelyTypedRoot, (err, subDirectories) => {
if (err) {
throw err;
@@ -120,9 +135,12 @@ function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, defini
throw err;
}
const tsFiles: string[] = [];
const testFiles: string[] = [];
let paramFile: string | undefined;
/** @type {string[]} */
const tsFiles = [];
/** @type {string[]} */
const testFiles = [];
/** @type {string | undefined} */
let paramFile;
for (const filePath of files.map(f => path.join(directoryPath, f))) {
if (filePathEndsWith(filePath, ".ts")) {
@@ -139,7 +157,7 @@ function importDefinitelyTypedTests(tscPath: string, rwcTestPath: string, defini
if (testFiles.length === 0) {
// no test files but multiple d.ts's, e.g. winjs
const regexp = new RegExp(d + "(([-][0-9])|([\.]d[\.]ts))");
const regexp = new RegExp(d + "(([-][0-9])|(\\.d\\.ts))");
if (tsFiles.length > 1 && tsFiles.every(t => filePathEndsWith(t, ".d.ts") && regexp.test(t))) {
for (const fileName of tsFiles) {
importDefinitelyTypedTest(tscPath, rwcTestPath, path.basename(fileName, ".d.ts"), [fileName], paramFile);
@@ -1,18 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "ES5",
"outDir": "./",
"rootDir": ".",
"newLine": "lf",
"noImplicitAny": true,
"strictNullChecks": true,
"sourceMap": false
},
"files": [
"../typings/node/node.d.ts",
"importDefinitelyTypedTests.ts"
],
"exclude": [
]
}
-20
View File
@@ -1,20 +0,0 @@
var fs = require("fs");
var path = require("path");
var hooks = [
"post-checkout"
];
hooks.forEach(function (hook) {
var hookInSourceControl = path.resolve(__dirname, "hooks", hook);
if (fs.existsSync(hookInSourceControl)) {
var hookInHiddenDirectory = path.resolve(__dirname, "..", ".git", "hooks", hook);
if (fs.existsSync(hookInHiddenDirectory)) {
fs.unlinkSync(hookInHiddenDirectory);
}
fs.linkSync(hookInSourceControl, hookInHiddenDirectory);
}
});
+25
View File
@@ -0,0 +1,25 @@
import fs from "fs";
import path from "path";
import url from "url";
import { findUpRoot } from "./build/findUpDir.mjs";
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
const hooks = [
"post-checkout"
];
hooks.forEach((hook) => {
const hookInSourceControl = path.resolve(__dirname, "hooks", hook);
if (fs.existsSync(hookInSourceControl)) {
const hookInHiddenDirectory = path.resolve(findUpRoot(), ".git", "hooks", hook);
if (fs.existsSync(hookInHiddenDirectory)) {
fs.unlinkSync(hookInHiddenDirectory);
}
fs.linkSync(hookInSourceControl, hookInHiddenDirectory);
}
});
@@ -1,11 +1,11 @@
/// <reference lib="esnext.asynciterable" />
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
/// <reference types="node" />
import { Octokit } from "@octokit/rest";
import { runSequence } from "./run-sequence";
import * as fs from "fs";
import * as path from "path";
import { runSequence } from "./run-sequence.mjs";
import fs from "fs";
import path from "path";
import url from "url";
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
const userName = process.env.GH_USERNAME;
const reviewers = process.env.REQUESTING_USER ? [process.env.REQUESTING_USER] : ["weswigham", "RyanCavanaugh"];
@@ -1,12 +1,8 @@
/// <reference lib="esnext.asynciterable" />
/// <reference lib="es2015.promise" />
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
import { Octokit } from "@octokit/rest";
import { runSequence } from "./run-sequence";
import { runSequence } from "./run-sequence.mjs";
const userName = process.env.GH_USERNAME || "typescript-bot";
const reviewers = process.env.REQUESTING_USER ? [process.env.REQUESTING_USER] : ["weswigham", "sandersn", "RyanCavanaugh"];
const now = new Date();
const masterBranchname = `user-baseline-updates`;
const targetBranch = process.env.TARGET_BRANCH || "main";
const branchName = process.env.TARGET_FORK?.toLowerCase() === "microsoft" && (targetBranch === "main" || targetBranch === "refs/heads/main")
@@ -22,7 +18,7 @@ runSequence([
["node", ["./node_modules/gulp/bin/gulp.js", "baseline-accept"]], // accept baselines
["git", ["checkout", "-b", branchName]], // create a branch
["git", ["add", "."]], // Add all changes
["git", ["commit", "-m", `"Update user baselines${+process.env.SOURCE_ISSUE! === 33716 ? " +cc @sandersn" : ""}"`]], // Commit all changes (ping nathan if we would post to CI thread)
["git", ["commit", "-m", `"Update user baselines${+(process.env.SOURCE_ISSUE ?? 0) === 33716 ? " +cc @sandersn" : ""}"`]], // Commit all changes (ping nathan if we would post to CI thread)
["git", ["push", "--set-upstream", "fork", branchName, "-f"]] // push the branch
]);
@@ -1,10 +1,8 @@
// @ts-check
/// <reference lib="esnext.asynciterable" />
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
const { Octokit } = require("@octokit/rest");
const fs = require("fs");
const ado = require("azure-devops-node-api");
const { default: fetch } = require("node-fetch");
import { Octokit } from "@octokit/rest";
import fs from "fs";
import ado from "azure-devops-node-api";
import fetch from "node-fetch";
import assert from "assert";
async function main() {
@@ -15,7 +13,7 @@ async function main() {
if (!requester) throw new Error("REQUESTING_USER environment variable not set.");
const buildId = process.env.BUILD_BUILDID;
if (!requester) throw new Error("BUILD_BUILDID environment variable not set.");
if (!buildId) throw new Error("BUILD_BUILDID environment variable not set.");
const postedComment = process.env.STATUS_COMMENT;
if (!postedComment) throw new Error("STATUS_COMMENT environment variable not set.");
@@ -36,10 +34,11 @@ async function main() {
const cli = new ado.WebApi("https://typescript.visualstudio.com/defaultcollection", ado.getHandlerFromToken("")); // Empty token, anon auth
const build = await cli.getBuildApi();
const artifact = await build.getArtifact("typescript", +buildId, "benchmark");
assert(artifact.resource?.url);
const updatedUrl = new URL(artifact.resource.url);
updatedUrl.search = `artifactName=benchmark&fileId=${artifact.resource.data}&fileName=manifest`;
const resp = await (await fetch(`${updatedUrl}`)).json();
for (const file of resp.items) {
for (const file of /** @type {any} */ (resp).items) {
if (/[\\/]linux\.benchmark$/.test(file.path)) {
const benchmarkUrl = new URL(artifact.resource.url);
benchmarkUrl.search = `artifactName=benchmark&fileId=${file.blob.id}&fileName=linux.benchmark`;
@@ -1,9 +1,7 @@
// @ts-check
/// <reference lib="esnext.asynciterable" />
// Must reference esnext.asynciterable lib, since octokit uses AsyncIterable internally
const { Octokit } = require("@octokit/rest");
const ado = require("azure-devops-node-api");
const { default: fetch } = require("node-fetch");
import { Octokit } from "@octokit/rest";
import assert from "assert";
import ado from "azure-devops-node-api";
import fetch from "node-fetch";
async function main() {
if (!process.env.SOURCE_ISSUE) {
@@ -16,10 +14,11 @@ async function main() {
const cli = new ado.WebApi("https://typescript.visualstudio.com/defaultcollection", ado.getHandlerFromToken("")); // Empty token, anon auth
const build = await cli.getBuildApi();
const artifact = await build.getArtifact("typescript", +process.env.BUILD_BUILDID, "tgz");
assert(artifact.resource?.url);
const updatedUrl = new URL(artifact.resource.url);
updatedUrl.search = `artifactName=tgz&fileId=${artifact.resource.data}&fileName=manifest`;
const resp = await (await fetch(`${updatedUrl}`)).json();
const file = resp.items[0];
const file = /** @type {any} */ (resp).items[0];
const tgzUrl = new URL(artifact.resource.url);
tgzUrl.search = `artifactName=tgz&fileId=${file.blob.id}&fileName=${file.path}`;
const link = "" + tgzUrl;
@@ -1,25 +1,29 @@
import * as path from "path";
import * as fs from "fs";
import path from "path";
import fs from "fs";
interface DiagnosticDetails {
/** @typedef {{
category: string;
code: number;
reportsUnnecessary?: {};
reportsDeprecated?: {};
isEarly?: boolean;
elidedInCompatabilityPyramid?: boolean;
}
}} DiagnosticDetails */
type InputDiagnosticMessageTable = Map<string, DiagnosticDetails>;
/** @typedef {Map<string, DiagnosticDetails>} InputDiagnosticMessageTable */
function main(): void {
function main() {
if (process.argv.length < 3) {
console.log("Usage:");
console.log("\tnode processDiagnosticMessages.js <diagnostic-json-input-file>");
console.log("\tnode processDiagnosticMessages.mjs <diagnostic-json-input-file>");
return;
}
function writeFile(fileName: string, contents: string) {
/**
* @param {string} fileName
* @param {string} contents
*/
function writeFile(fileName, contents) {
fs.writeFile(path.join(path.dirname(inputFilePath), fileName), contents, { encoding: "utf-8" }, err => {
if (err) throw err;
});
@@ -29,9 +33,11 @@ function main(): void {
console.log(`Reading diagnostics from ${inputFilePath}`);
const inputStr = fs.readFileSync(inputFilePath, { encoding: "utf-8" });
const diagnosticMessagesJson: { [key: string]: DiagnosticDetails } = JSON.parse(inputStr);
/** @type {{ [key: string]: DiagnosticDetails }} */
const diagnosticMessagesJson = JSON.parse(inputStr);
const diagnosticMessages: InputDiagnosticMessageTable = new Map();
/** @type {InputDiagnosticMessageTable} */
const diagnosticMessages = new Map();
for (const key in diagnosticMessagesJson) {
if (Object.hasOwnProperty.call(diagnosticMessagesJson, key)) {
diagnosticMessages.set(key, diagnosticMessagesJson[key]);
@@ -49,8 +55,12 @@ function main(): void {
writeFile("diagnosticMessages.generated.json", messageOutput);
}
function checkForUniqueCodes(diagnosticTable: InputDiagnosticMessageTable) {
const allCodes: { [key: number]: true | undefined } = [];
/**
* @param {InputDiagnosticMessageTable} diagnosticTable
*/
function checkForUniqueCodes(diagnosticTable) {
/** @type {Record<number, true | undefined>} */
const allCodes = [];
diagnosticTable.forEach(({ code }) => {
if (allCodes[code]) {
throw new Error(`Diagnostic code ${code} appears more than once.`);
@@ -59,7 +69,13 @@ function checkForUniqueCodes(diagnosticTable: InputDiagnosticMessageTable) {
});
}
function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, inputFilePathRel: string, thisFilePathRel: string): string {
/**
* @param {InputDiagnosticMessageTable} messageTable
* @param {string} inputFilePathRel
* @param {string} thisFilePathRel
* @returns {string}
*/
function buildInfoFileOutput(messageTable, inputFilePathRel, thisFilePathRel) {
let result =
"// <auto-generated />\r\n" +
"// generated from '" + inputFilePathRel + "' in '" + thisFilePathRel.replace(/\\/g, "/") + "'\r\n" +
@@ -83,27 +99,37 @@ function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, inputFil
return result;
}
function buildDiagnosticMessageOutput(messageTable: InputDiagnosticMessageTable): string {
let result = "{";
/**
* @param {InputDiagnosticMessageTable} messageTable
* @returns {string}
*/
function buildDiagnosticMessageOutput(messageTable) {
/** @type {Record<string, string>} */
const result = {};
messageTable.forEach(({ code }, name) => {
const propName = convertPropertyName(name);
result += `\r\n "${createKey(propName, code)}" : "${name.replace(/[\"]/g, '\\"')}",`;
result[createKey(propName, code)] = name;
});
// Shave trailing comma, then add newline and ending brace
result = result.slice(0, result.length - 1) + "\r\n}";
// Assert that we generated valid JSON
JSON.parse(result);
return result;
return JSON.stringify(result, undefined, 2).replace(/\r?\n/g, "\r\n");
}
function createKey(name: string, code: number): string {
/**
*
* @param {string} name
* @param {number} code
* @returns {string}
*/
function createKey(name, code) {
return name.slice(0, 100) + "_" + code;
}
function convertPropertyName(origName: string): string {
/**
* @param {string} origName
* @returns {string}
*/
function convertPropertyName(origName) {
let result = origName.split("").map(char => {
if (char === "*") return "_Asterisk";
if (char === "/") return "_Slash";
@@ -1,9 +1,11 @@
/// <reference types="node" />
import childProcess from "child_process";
import fs from "fs-extra";
import path from "path";
import glob from "glob";
import url from "url";
import * as childProcess from "child_process";
import * as fs from "fs-extra";
import * as path from "path";
import * as glob from "glob";
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
const root = path.join(__dirname, "..");
const source = path.join(root, "built/local");
@@ -45,7 +47,7 @@ async function copyTypesMap() {
}
async function buildProtocol() {
const protocolScript = path.join(__dirname, "buildProtocol.js");
const protocolScript = path.join(__dirname, "buildProtocol.mjs");
if (!fs.existsSync(protocolScript)) {
throw new Error(`Expected protocol script ${protocolScript} to exist`);
}
@@ -80,16 +82,26 @@ async function writeGitAttributes() {
await fs.writeFile(path.join(dest, ".gitattributes"), `* text eol=lf`, "utf-8");
}
async function copyWithCopyright(fileName: string, destName = fileName) {
/**
* @param {string} fileName
* @param {string} destName
*/
async function copyWithCopyright(fileName, destName = fileName) {
const content = await fs.readFile(path.join(source, fileName), "utf-8");
await fs.writeFile(path.join(dest, destName), copyright + "\n" + content);
}
async function copyFromBuiltLocal(fileName: string) {
/**
* @param {string} fileName
*/
async function copyFromBuiltLocal(fileName) {
await fs.copy(path.join(source, fileName), path.join(dest, fileName));
}
async function copyFilesWithGlob(pattern: string) {
/**
* @param {string} pattern
*/
async function copyFilesWithGlob(pattern) {
const files = glob.sync(pattern, { cwd: source }).map(f => path.basename(f));
for (const f of files) {
await copyFromBuiltLocal(f);
@@ -97,7 +109,11 @@ async function copyFilesWithGlob(pattern: string) {
console.log(`Copied ${files.length} files matching pattern ${pattern}`);
}
async function exec(path: string, args: string[] = []) {
/**
* @param {string} path
* @param {string[]} args
*/
async function exec(path, args = []) {
const cmdLine = ["node", path, ...args].join(" ");
console.log(cmdLine);
childProcess.execSync(cmdLine);
@@ -1,6 +1,8 @@
const MAX_UNICODE_CODEPOINT = 0x10FFFF;
/** @type {(c: string) => boolean} */
const isStart = c => /[\p{ID_Start}\u{2118}\u{212E}\u{309B}\u{309C}]/u.test(c); // Other_ID_Start explicitly included for back compat - see http://www.unicode.org/reports/tr31/#Introduction
/** @type {(c: string) => boolean} */
const isPart = c => /[\p{ID_Continue}\u{00B7}\u{0387}\u{19DA}\u{1369}\u{136A}\u{136B}\u{136C}\u{136D}\u{136E}\u{136F}\u{1370}\u{1371}]/u.test(c) || isStart(c); // Likewise for Other_ID_Continue
const parts = [];
let partsActive = false;
@@ -1,7 +1,5 @@
/// <reference lib="esnext.asynciterable" />
/// <reference lib="es2015.promise" />
import { Octokit } from "@octokit/rest";
import * as minimist from "minimist";
import minimist from "minimist";
const options = minimist(process.argv.slice(2), {
boolean: ["help"],
@@ -55,7 +53,10 @@ async function main() {
}
}
function printHelpAndExit(exitCode: number) {
/**
* @param {number} exitCode
*/
function printHelpAndExit(exitCode) {
console.log(`
usage: request-pr-review.js [options]
-3
View File
@@ -1,3 +0,0 @@
import { SpawnSyncOptions } from "child_process";
export function runSequence(tasks: [string, string[]][], opts?: SpawnSyncOptions): string;
@@ -1,10 +1,12 @@
// @ts-check
const cp = require("child_process");
import assert from "assert";
import cp from "child_process";
/**
* @param {[string, string[]][]} tasks
* @param {cp.SpawnSyncOptions} opts
* @returns {string}
*/
function runSequence(tasks, opts = { timeout: 100000, shell: true }) {
export function runSequence(tasks, opts = { timeout: 100000, shell: true }) {
let lastResult;
for (const task of tasks) {
console.log(`${task[0]} ${task[1].join(" ")}`);
@@ -13,7 +15,7 @@ function runSequence(tasks, opts = { timeout: 100000, shell: true }) {
console.log(result.stdout && result.stdout.toString());
lastResult = result;
}
return lastResult && lastResult.stdout && lastResult.stdout.toString();
const out = lastResult?.stdout?.toString();
assert(out !== undefined);
return out;
}
exports.runSequence = runSequence;
+22 -9
View File
@@ -1,15 +1,28 @@
{
"compilerOptions": {
"lib": [
"es2018"
],
"module": "Node16",
"moduleResolution": "Node16",
"target": "es2018",
"noEmit": true,
// "declaration": true,
// "emitDeclarationOnly": true,
"strict": true,
"removeComments": false,
"declaration": false,
"sourceMap": true,
"newLine": "lf",
"target": "es6",
"module": "commonjs",
"types": ["node"],
"lib": ["es6", "scripthost"],
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowUnusedLabels": false,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"allowJs": true,
"checkJs": true
},
"include": ["*.ts"]
"include": [
"**/*.mjs", "**/*.cjs"
]
}
@@ -1,7 +1,5 @@
// @ts-check
/// <reference lib="esnext.asynciterable" />
const { Octokit } = require("@octokit/rest");
const { runSequence } = require("./run-sequence");
import { Octokit } from "@octokit/rest";
import { runSequence } from "./run-sequence.mjs";
// The first is used by bot-based kickoffs, the second by automatic triggers
const triggeredPR = process.env.SOURCE_ISSUE || process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER;
@@ -46,7 +44,7 @@ async function main() {
const inputPR = await gh.pulls.get({ owner: "Microsoft", repo: "TypeScript", pull_number: num });
// GH calculates the rebaseable-ness of a PR into its target, so we can just use that here
if (!inputPR.data.rebaseable) {
if (+triggeredPR === num) {
if (+(triggeredPR ?? 0) === num) {
await gh.issues.createComment({
owner: "Microsoft",
repo: "TypeScript",
+122
View File
@@ -0,0 +1,122 @@
declare namespace Word {
export interface Collection<T> {
count: number;
item(index: number): T;
}
export interface Font {
bold: boolean;
italic: boolean;
subscript: boolean;
superscript: boolean;
}
export interface Find {
font: Font;
format: boolean;
replacement: Replacement;
style: any;
text: string;
clearFormatting(): void;
execute(
findText: string,
matchCase: boolean,
matchWholeWord: boolean,
matchWildcards: boolean,
matchSoundsLike: boolean,
matchAllWordForms: boolean,
forward: boolean,
wrap: number,
format: boolean,
replaceWith: string,
replace: number): boolean;
}
export interface Replacement {
font: Font;
style: any;
text: string;
clearFormatting(): void;
}
export interface ListFormat {
listLevelNumber: number;
listString: string;
}
export interface Column {
}
export interface Columns extends Collection<Column> {
}
export interface Table {
columns: Columns;
}
export interface Tables extends Collection<Table> {
}
export interface Range {
find: Find;
listFormat: ListFormat;
tables: Tables;
text: string;
textRetrievalMode: {
includeHiddenText: boolean;
}
words: Ranges;
}
export interface Ranges extends Collection<Range> {
}
export interface Style {
nameLocal: string;
}
export interface Paragraph {
alignment: number;
range: Range;
style: Style;
next(): Paragraph;
}
export interface Paragraphs extends Collection<Paragraph> {
first: Paragraph;
}
export interface Field {
}
export interface Fields extends Collection<Field> {
toggleShowCodes(): void;
}
export interface Hyperlink {
address: string;
textToDisplay: string;
range: Range;
}
export interface Hyperlinks extends Collection<Hyperlink> {
}
export interface Document {
fields: Fields;
paragraphs: Paragraphs;
hyperlinks: Hyperlinks;
builtInDocumentProperties: Collection<any>;
close(saveChanges: boolean): void;
range(): Range;
}
export interface Documents extends Collection<Document> {
open(filename: string): Document;
}
export interface Application {
documents: Documents;
quit(): void;
}
}
+61 -142
View File
@@ -7,145 +7,32 @@
// as a command line argument and the resulting Markdown is written to standard output. The
// tool recognizes the specific Word styles used in the TypeScript Language Specification.
namespace Word {
export interface Collection<T> {
count: number;
item(index: number): T;
}
export interface Font {
bold: boolean;
italic: boolean;
subscript: boolean;
superscript: boolean;
}
export interface Find {
font: Font;
format: boolean;
replacement: Replacement;
style: any;
text: string;
clearFormatting(): void;
execute(
findText: string,
matchCase: boolean,
matchWholeWord: boolean,
matchWildcards: boolean,
matchSoundsLike: boolean,
matchAllWordForms: boolean,
forward: boolean,
wrap: number,
format: boolean,
replaceWith: string,
replace: number): boolean;
}
export interface Replacement {
font: Font;
style: any;
text: string;
clearFormatting(): void;
}
export interface ListFormat {
listLevelNumber: number;
listString: string;
}
export interface Column {
}
export interface Columns extends Collection<Column> {
}
export interface Table {
columns: Columns;
}
export interface Tables extends Collection<Table> {
}
export interface Range {
find: Find;
listFormat: ListFormat;
tables: Tables;
text: string;
textRetrievalMode: {
includeHiddenText: boolean;
}
words: Ranges;
}
export interface Ranges extends Collection<Range> {
}
export interface Style {
nameLocal: string;
}
export interface Paragraph {
alignment: number;
range: Range;
style: Style;
next(): Paragraph;
}
export interface Paragraphs extends Collection<Paragraph> {
first: Paragraph;
}
export interface Field {
}
export interface Fields extends Collection<Field> {
toggleShowCodes(): void;
}
export interface Hyperlink {
address: string;
textToDisplay: string;
range: Range;
}
export interface Hyperlinks extends Collection<Hyperlink> {
}
export interface Document {
fields: Fields;
paragraphs: Paragraphs;
hyperlinks: Hyperlinks;
builtInDocumentProperties: Collection<any>;
close(saveChanges: boolean): void;
range(): Range;
}
export interface Documents extends Collection<Document> {
open(filename: string): Document;
}
export interface Application {
documents: Documents;
quit(): void;
}
}
/// <reference lib="scripthost" />
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./word.d.ts" />
/** @type {{
args: string[];
createObject: (typeName: string) => any;
write(s: string): void;
writeFile: (fileName: string, data: string) => void;
}} */
const sys = (() => {
const fileStream = new ActiveXObject("ADODB.Stream");
fileStream.Type = 2 /* text */;
const binaryStream = new ActiveXObject("ADODB.Stream");
binaryStream.Type = 1 /* binary */;
const args: string[] = [];
const args = [];
for (let i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
args,
createObject: (typeName: string) => new ActiveXObject(typeName),
write(s: string): void {
createObject: (typeName) => new ActiveXObject(typeName),
write(s) {
WScript.StdOut.Write(s);
},
writeFile: (fileName: string, data: string): void => {
writeFile: (fileName, data) => {
fileStream.Open();
binaryStream.Open();
try {
@@ -165,25 +52,37 @@ const sys = (() => {
};
})();
interface FindReplaceOptions {
/** @typedef {{
style?: any;
font?: {
bold?: boolean;
italic?: boolean;
subscript?: boolean;
};
}
}} FindReplaceOptions */
function convertDocumentToMarkdown(doc: Word.Document): string {
const columnAlignment: number[] = [];
let tableColumnCount: number;
let tableCellIndex: number;
let lastInTable: boolean;
let lastStyle: string;
/**
* @param {Word.Document} doc
* @returns {string}
*/
function convertDocumentToMarkdown(doc) {
/** @type {number[]} */
const columnAlignment = [];
/** @type {number} */
let tableColumnCount;
/** @type {number} */
let tableCellIndex;
/** @type {boolean} */
let lastInTable;
/** @type {string} */
let lastStyle;
let result = "";
function setProperties(target: any, properties: any) {
/**
* @param {any} target
* @param {any} properties
*/
function setProperties(target, properties) {
for (const name in properties) {
if (Object.prototype.hasOwnProperty.call(properties, name)) {
const value = properties[name];
@@ -197,7 +96,13 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
}
}
function findReplace(findText: string, findOptions: FindReplaceOptions, replaceText: string, replaceOptions: FindReplaceOptions) {
/**
* @param {string} findText
* @param {FindReplaceOptions} findOptions
* @param {string} replaceText
* @param {FindReplaceOptions} replaceOptions
*/
function findReplace(findText, findOptions, replaceText, replaceOptions) {
const find = doc.range().find;
find.clearFormatting();
setProperties(find, findOptions);
@@ -230,7 +135,10 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
}
}
function write(s: string) {
/**
* @param {string} s
*/
function write(s) {
result += s;
}
@@ -250,7 +158,10 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
write("|\n");
}
function trimEndFormattingMarks(text: string) {
/**
* @param {string} text
*/
function trimEndFormattingMarks(text) {
let i = text.length;
while (i > 0 && text.charCodeAt(i - 1) < 0x20) i--;
return text.substr(0, i);
@@ -269,7 +180,10 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
}
}
function writeParagraph(p: Word.Paragraph) {
/**
* @param {Word.Paragraph} p
*/
function writeParagraph(p) {
const range = p.range;
const inTable = range.tables.count > 0;
@@ -408,12 +322,17 @@ function convertDocumentToMarkdown(doc: Word.Document): string {
return result;
}
function main(args: string[]) {
/**
* @param {string[]} args
*/
function main(args) {
if (args.length !== 2) {
sys.write("Syntax: word2md <inputfile> <outputfile>\n");
return;
}
const app: Word.Application = sys.createObject("Word.Application");
/** @type {Word.Application} */
const app = sys.createObject("Word.Application");
const doc = app.documents.open(args[0]);
sys.writeFile(args[1], convertDocumentToMarkdown(doc));
doc.close(/* saveChanges */ false);
+18 -5
View File
@@ -173,10 +173,16 @@ namespace ts {
const oldCompilerOptions = useOldState ? oldState!.compilerOptions : undefined;
const canCopySemanticDiagnostics = useOldState && oldState!.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
!compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions!);
// We can only reuse emit signatures (i.e. .d.ts signatures) if the .d.ts file is unchanged,
// which will eg be depedent on change in options like declarationDir and outDir options are unchanged.
// We need to look in oldState.compilerOptions, rather than oldCompilerOptions (i.e.we need to disregard useOldState) because
// oldCompilerOptions can be undefined if there was change in say module from None to some other option
// which would make useOldState as false since we can now use reference maps that are needed to track what to emit, what to check etc
// but that option change does not affect d.ts file name so emitSignatures should still be reused.
const canCopyEmitSignatures = compilerOptions.composite &&
oldState?.emitSignatures &&
!outFilePath &&
!compilerOptionsAffectDeclarationPath(compilerOptions, oldCompilerOptions!);
!compilerOptionsAffectDeclarationPath(compilerOptions, oldState.compilerOptions);
if (useOldState) {
// Copy old state's changed files set
oldState!.changedFilesSet?.forEach(value => state.changedFilesSet.add(value));
@@ -764,7 +770,7 @@ namespace ts {
export type ProgramBuildInfoFileId = number & { __programBuildInfoFileIdBrand: any };
export type ProgramBuildInfoFileIdListId = number & { __programBuildInfoFileIdListIdBrand: any };
export type ProgramBuildInfoDiagnostic = ProgramBuildInfoFileId | [fileId: ProgramBuildInfoFileId, diagnostics: readonly ReusableDiagnostic[]];
export type ProgramBuilderInfoFilePendingEmit = [fileId: ProgramBuildInfoFileId, emitKind: BuilderFileEmit];
export type ProgramBuilderInfoFilePendingEmit = ProgramBuildInfoFileId | [fileId: ProgramBuildInfoFileId];
export type ProgramBuildInfoReferencedMap = [fileId: ProgramBuildInfoFileId, fileIdListId: ProgramBuildInfoFileIdListId][];
export type ProgramBuildInfoBuilderStateFileInfo = Omit<BuilderState.FileInfo, "signature"> & {
/**
@@ -917,7 +923,10 @@ namespace ts {
const seenFiles = new Set<Path>();
for (const path of state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(compareStringsCaseSensitive)) {
if (tryAddToSet(seenFiles, path)) {
(affectedFilesPendingEmit ||= []).push([toFileId(path), state.affectedFilesPendingEmitKind!.get(path)!]);
const fileId = toFileId(path), emitKind = state.affectedFilesPendingEmitKind!.get(path)!;
(affectedFilesPendingEmit ||= []).push(
emitKind === BuilderFileEmit.Full ? fileId : [fileId]
);
}
}
}
@@ -1469,6 +1478,10 @@ namespace ts {
{ version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat };
}
export function toBuilderFileEmit(value: ProgramBuilderInfoFilePendingEmit): BuilderFileEmit{
return isNumber(value) ? BuilderFileEmit.Full : BuilderFileEmit.DtsOnly;
}
export function createBuilderProgramUsingProgramBuildInfo(program: ProgramBuildInfo, buildInfoPath: string, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram {
const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames());
@@ -1507,8 +1520,8 @@ namespace ts {
exportedModulesMap: toManyToManyPathMap(program.exportedModulesMap),
semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toFilePath(isNumber(value) ? value : value[0]), value => isNumber(value) ? emptyArray : value[1]),
hasReusableDiagnostic: true,
affectedFilesPendingEmit: map(program.affectedFilesPendingEmit, value => toFilePath(value[0])),
affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toFilePath(value[0]), value => value[1]),
affectedFilesPendingEmit: map(program.affectedFilesPendingEmit, value => toFilePath(isNumber(value) ? value : value[0])),
affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, value => toFilePath(isNumber(value) ? value : value[0]), toBuilderFileEmit),
affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
changedFilesSet: new Set(map(program.changeFileSet, toFilePath)),
latestChangedDtsFile,
+238 -163
View File
@@ -194,8 +194,6 @@ namespace ts {
None = 0,
Source = 1 << 0,
Target = 1 << 1,
PropertyCheck = 1 << 2,
InPropertyCheck = 1 << 3,
}
const enum RecursionFlags {
@@ -642,6 +640,11 @@ namespace ts {
getOptionalType: () => optionalType,
getPromiseType: () => getGlobalPromiseType(/*reportErrors*/ false),
getPromiseLikeType: () => getGlobalPromiseLikeType(/*reportErrors*/ false),
getAsyncIterableType: () => {
const type = getGlobalAsyncIterableType(/*reportErrors*/ false);
if (type === emptyGenericType) return undefined;
return type;
},
isSymbolAccessible,
isArrayType,
isTupleType,
@@ -1537,9 +1540,9 @@ namespace ts {
return symbol;
}
if (symbol.flags & SymbolFlags.Alias) {
const target = resolveAlias(symbol);
// Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
if (target === unknownSymbol || target.flags & meaning) {
const targetFlags = getAllSymbolFlags(symbol);
// `targetFlags` will be `SymbolFlags.All` if an error occurred in alias resolution; this avoids cascading errors
if (targetFlags & meaning) {
return symbol;
}
}
@@ -2226,8 +2229,8 @@ namespace ts {
!checkAndReportErrorForExtendingInterface(errorLocation) &&
!checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
!checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
!checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
!checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
let suggestion: Symbol | undefined;
let suggestedLib: string | undefined;
@@ -2320,7 +2323,7 @@ namespace ts {
}
}
if (result && errorLocation && meaning & SymbolFlags.Value && result.flags & SymbolFlags.Alias && !(result.flags & SymbolFlags.Value) && !isValidTypeOnlyAliasUseSite(errorLocation)) {
const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result);
const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result, SymbolFlags.Value);
if (typeOnlyDeclaration) {
const message = typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier
? Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
@@ -2515,7 +2518,7 @@ namespace ts {
}
function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean {
if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) {
if (meaning & SymbolFlags.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));
@@ -2526,7 +2529,8 @@ namespace ts {
return true;
}
const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) {
const allFlags = symbol && getAllSymbolFlags(symbol);
if (symbol && allFlags !== undefined && !(allFlags & SymbolFlags.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);
@@ -2577,9 +2581,9 @@ namespace ts {
return false;
}
function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean {
if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule & ~SymbolFlags.Type)) {
const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.NamespaceModule & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
function checkAndReportErrorForUsingNamespaceAsTypeOrValue(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean {
if (meaning & (SymbolFlags.Value & ~SymbolFlags.Type)) {
const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.NamespaceModule, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol) {
error(
errorLocation,
@@ -2588,8 +2592,8 @@ namespace ts {
return true;
}
}
else if (meaning & (SymbolFlags.Type & ~SymbolFlags.NamespaceModule & ~SymbolFlags.Value)) {
const symbol = resolveSymbol(resolveName(errorLocation, name, (SymbolFlags.ValueModule | SymbolFlags.NamespaceModule) & ~SymbolFlags.Type, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
else if (meaning & (SymbolFlags.Type & ~SymbolFlags.Value)) {
const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Module, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false));
if (symbol) {
error(errorLocation, Diagnostics.Cannot_use_namespace_0_as_a_type, unescapeLeadingUnderscores(name));
return true;
@@ -3237,6 +3241,54 @@ namespace ts {
return undefined;
}
/**
* Gets combined flags of a `symbol` and all alias targets it resolves to. `resolveAlias`
* is typically recursive over chains of aliases, but stops mid-chain if an alias is merged
* with another exported symbol, e.g.
* ```ts
* // a.ts
* export const a = 0;
* // b.ts
* export { a } from "./a";
* export type a = number;
* // c.ts
* import { a } from "./b";
* ```
* Calling `resolveAlias` on the `a` in c.ts would stop at the merged symbol exported
* from b.ts, even though there is still more alias to resolve. Consequently, if we were
* trying to determine if the `a` in c.ts has a value meaning, looking at the flags on
* the local symbol and on the symbol returned by `resolveAlias` is not enough.
* @returns SymbolFlags.All if `symbol` is an alias that ultimately resolves to `unknown`;
* combined flags of all alias targets otherwise.
*/
function getAllSymbolFlags(symbol: Symbol): SymbolFlags {
let flags = symbol.flags;
let seenSymbols;
while (symbol.flags & SymbolFlags.Alias) {
const target = resolveAlias(symbol);
if (target === unknownSymbol) {
return SymbolFlags.All;
}
// Optimizations - try to avoid creating or adding to
// `seenSymbols` if possible
if (target === symbol || seenSymbols?.has(target)) {
break;
}
if (target.flags & SymbolFlags.Alias) {
if (seenSymbols) {
seenSymbols.add(target);
}
else {
seenSymbols = new Set([symbol, target]);
}
}
flags |= target.flags;
symbol = target;
}
return flags;
}
/**
* Marks a symbol as type-only if its declaration is syntactically type-only.
* If it is not itself marked type-only, but resolves to a type-only alias
@@ -3289,12 +3341,18 @@ namespace ts {
}
/** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
function getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined {
function getTypeOnlyAliasDeclaration(symbol: Symbol, include?: SymbolFlags): TypeOnlyAliasDeclaration | undefined {
if (!(symbol.flags & SymbolFlags.Alias)) {
return undefined;
}
const links = getSymbolLinks(symbol);
return links.typeOnlyDeclaration || undefined;
if (include === undefined) {
return links.typeOnlyDeclaration || undefined;
}
if (links.typeOnlyDeclaration) {
return getAllSymbolFlags(resolveAlias(links.typeOnlyDeclaration.symbol)) & include ? links.typeOnlyDeclaration : undefined;
}
return undefined;
}
function markExportAsReferenced(node: ImportEqualsDeclaration | ExportSpecifier) {
@@ -3302,7 +3360,7 @@ namespace ts {
const target = resolveAlias(symbol);
if (target) {
const markAlias = target === unknownSymbol ||
((target.flags & SymbolFlags.Value) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
((getAllSymbolFlags(target) & SymbolFlags.Value) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol, SymbolFlags.Value));
if (markAlias) {
markAliasSymbolAsReferenced(symbol);
@@ -3323,8 +3381,7 @@ namespace ts {
// This way a chain of imports can be elided if ultimately the final input is only used in a type
// position.
if (isInternalModuleImportEqualsDeclaration(node)) {
const target = resolveSymbol(symbol);
if (target === unknownSymbol || target.flags & SymbolFlags.Value) {
if (getAllSymbolFlags(resolveSymbol(symbol)) & SymbolFlags.Value) {
// import foo = <symbol>
checkExpressionCached(node.moduleReference as Expression);
}
@@ -4250,7 +4307,7 @@ namespace ts {
function symbolIsValue(symbol: Symbol, includeTypeOnlyMembers?: boolean): boolean {
return !!(
symbol.flags & SymbolFlags.Value ||
symbol.flags & SymbolFlags.Alias && resolveAlias(symbol).flags & SymbolFlags.Value && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol)));
symbol.flags & SymbolFlags.Alias && getAllSymbolFlags(symbol) & SymbolFlags.Value && (includeTypeOnlyMembers || !getTypeOnlyAliasDeclaration(symbol)));
}
function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration | undefined {
@@ -4544,8 +4601,10 @@ namespace ts {
}
// Qualify if the symbol from symbol table has same meaning as expected
symbolFromSymbolTable = (symbolFromSymbolTable.flags & SymbolFlags.Alias && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
if (symbolFromSymbolTable.flags & meaning) {
const shouldResolveAlias = (symbolFromSymbolTable.flags & SymbolFlags.Alias && !getDeclarationOfKind(symbolFromSymbolTable, SyntaxKind.ExportSpecifier));
symbolFromSymbolTable = shouldResolveAlias ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
const flags = shouldResolveAlias ? getAllSymbolFlags(symbolFromSymbolTable) : symbolFromSymbolTable.flags;
if (flags & meaning) {
qualify = true;
return true;
}
@@ -7176,16 +7235,6 @@ namespace ts {
return statements;
}
function canHaveExportModifier(node: Statement): node is Extract<HasModifiers, Statement> {
return isEnumDeclaration(node) ||
isVariableStatement(node) ||
isFunctionDeclaration(node) ||
isClassDeclaration(node) ||
(isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)) ||
isInterfaceDeclaration(node) ||
isTypeDeclaration(node);
}
function addExportModifier(node: Extract<HasModifiers, Statement>) {
const flags = (getEffectiveModifierFlags(node) | ModifierFlags.Export) & ~ModifierFlags.Ambient;
return factory.updateModifiers(node, flags);
@@ -7519,7 +7568,7 @@ namespace ts {
}
function isTypeOnlyNamespace(symbol: Symbol) {
return every(getNamespaceMembersForSerialization(symbol), m => !(resolveSymbol(m).flags & SymbolFlags.Value));
return every(getNamespaceMembersForSerialization(symbol), m => !(getAllSymbolFlags(resolveSymbol(m)) & SymbolFlags.Value));
}
function serializeModule(symbol: Symbol, symbolName: string, modifierFlags: ModifierFlags) {
@@ -10017,7 +10066,7 @@ namespace ts {
links.type = exportSymbol?.declarations && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations!.length ? getFlowTypeFromCommonJSExport(exportSymbol)
: isDuplicatedCommonJSExport(symbol.declarations) ? autoType
: declaredType ? declaredType
: targetSymbol.flags & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol)
: getAllSymbolFlags(targetSymbol) & SymbolFlags.Value ? getTypeOfSymbol(targetSymbol)
: errorType;
}
return links.type;
@@ -12012,7 +12061,20 @@ namespace ts {
}
function isGenericMappedType(type: Type): type is MappedType {
return !!(getObjectFlags(type) & ObjectFlags.Mapped) && isGenericIndexType(getConstraintTypeFromMappedType(type as MappedType));
if (getObjectFlags(type) & ObjectFlags.Mapped) {
const constraint = getConstraintTypeFromMappedType(type as MappedType);
if (isGenericIndexType(constraint)) {
return true;
}
// A mapped type is generic if the 'as' clause references generic types other than the iteration type.
// To determine this, we substitute the constraint type (that we now know isn't generic) for the iteration
// type and check whether the resulting type is generic.
const nameType = getNameTypeFromMappedType(type as MappedType);
if (nameType && isGenericIndexType(instantiateType(nameType, makeUnaryTypeMapper(getTypeParameterFromMappedType(type as MappedType), constraint)))) {
return true;
}
}
return false;
}
function resolveStructuredTypeMembers(type: StructuredType): ResolvedType {
@@ -12510,7 +12572,7 @@ namespace ts {
let indexTypes: Type[] | undefined;
const isUnion = containingType.flags & TypeFlags.Union;
// Flags we want to propagate to the result if they exist in all source symbols
let optionalFlag = isUnion ? SymbolFlags.None : SymbolFlags.Optional;
let optionalFlag: SymbolFlags | undefined;
let syntheticFlag = CheckFlags.SyntheticMethod;
let checkFlags = isUnion ? 0 : CheckFlags.Readonly;
let mergedInstantiations = false;
@@ -12520,11 +12582,14 @@ namespace ts {
const prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
const modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0;
if (prop) {
if (isUnion) {
optionalFlag |= (prop.flags & SymbolFlags.Optional);
}
else {
optionalFlag &= prop.flags;
if (prop.flags & SymbolFlags.ClassMember) {
optionalFlag ??= isUnion ? SymbolFlags.None : SymbolFlags.Optional;
if (isUnion) {
optionalFlag |= (prop.flags & SymbolFlags.Optional);
}
else {
optionalFlag &= prop.flags;
}
}
if (!singleProp) {
singleProp = prop;
@@ -12643,7 +12708,7 @@ namespace ts {
propTypes.push(type);
}
addRange(propTypes, indexTypes);
const result = createSymbol(SymbolFlags.Property | optionalFlag, name, syntheticFlag | checkFlags);
const result = createSymbol(SymbolFlags.Property | (optionalFlag ?? 0), name, syntheticFlag | checkFlags);
result.containingType = containingType;
if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
result.valueDeclaration = firstValueDeclaration;
@@ -15574,8 +15639,14 @@ namespace ts {
return getStringLiteralType(text);
}
newTexts.push(text);
if (every(newTexts, t => t === "") && every(newTypes, t => !!(t.flags & TypeFlags.String))) {
return stringType;
if (every(newTexts, t => t === "")) {
if (every(newTypes, t => !!(t.flags & TypeFlags.String))) {
return stringType;
}
// Normalize `${Mapping<xxx>}` into Mapping<xxx>
if (newTypes.length === 1 && isPatternLiteralType(newTypes[0])) {
return newTypes[0];
}
}
const id = `${getTypeListId(newTypes)}|${map(newTexts, t => t.length).join(",")}|${newTexts.join("")}`;
let type = templateLiteralTypes.get(id);
@@ -15634,11 +15705,13 @@ namespace ts {
function getStringMappingType(symbol: Symbol, type: Type): Type {
return type.flags & (TypeFlags.Union | TypeFlags.Never) ? mapType(type, t => getStringMappingType(symbol, t)) :
// Mapping<Mapping<T>> === Mapping<T>
type.flags & TypeFlags.StringMapping && symbol === type.symbol ? type :
isGenericIndexType(type) || isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, isPatternLiteralPlaceholderType(type) && !(type.flags & TypeFlags.StringMapping) ? getTemplateLiteralType(["", ""], [type]) : type) :
type.flags & TypeFlags.StringLiteral ? getStringLiteralType(applyStringMapping(symbol, (type as StringLiteralType).value)) :
type.flags & TypeFlags.TemplateLiteral ? getTemplateLiteralType(...applyTemplateStringMapping(symbol, (type as TemplateLiteralType).texts, (type as TemplateLiteralType).types)) :
// Mapping<Mapping<T>> === Mapping<T>
type.flags & TypeFlags.StringMapping && symbol === type.symbol ? type :
type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.StringMapping) || isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) :
// This handles Mapping<`${number}`> and Mapping<`${bigint}`>
isPatternLiteralPlaceholderType(type) ? getStringMappingTypeForGenericType(symbol, getTemplateLiteralType(["", ""], [type])) :
type;
}
@@ -15936,11 +16009,12 @@ namespace ts {
}
function isPatternLiteralPlaceholderType(type: Type): boolean {
return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) || !!(type.flags & TypeFlags.StringMapping && isPatternLiteralPlaceholderType((type as StringMappingType).type));
return !!(type.flags & (TypeFlags.Any | TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) || isPatternLiteralType(type);
}
function isPatternLiteralType(type: Type) {
return !!(type.flags & TypeFlags.TemplateLiteral) && every((type as TemplateLiteralType).types, isPatternLiteralPlaceholderType);
return !!(type.flags & TypeFlags.TemplateLiteral) && every((type as TemplateLiteralType).types, isPatternLiteralPlaceholderType) ||
!!(type.flags & TypeFlags.StringMapping) && isPatternLiteralPlaceholderType((type as StringMappingType).type);
}
function isGenericType(type: Type): boolean {
@@ -16288,11 +16362,7 @@ namespace ts {
}
}
}
// We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
// if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
// "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
// so in those cases we refain from performing inference and retain the uninfered type parameter
if (!checkTypeInstantiable || !some(root.inferTypeParameters, t => t === extendsType)) {
if (!checkTypeInstantiable) {
// We don't want inferences from constraints as they may cause us to eagerly resolve the
// conditional type instead of deferring resolution. Also, we always want strict function
// types rules (i.e. proper contravariance) for inferences.
@@ -19026,7 +19096,7 @@ namespace ts {
}
}
const isPerformingCommonPropertyChecks = (relation !== comparableRelation || !(source.flags & TypeFlags.Union) && isLiteralType(source)) &&
const isPerformingCommonPropertyChecks = (relation !== comparableRelation || isUnitType(source)) &&
!(intersectionState & IntersectionState.Target) &&
source.flags & (TypeFlags.Primitive | TypeFlags.Object | TypeFlags.Intersection) && source !== globalObjectType &&
target.flags & (TypeFlags.Object | TypeFlags.Intersection) && isWeakType(target) &&
@@ -19053,31 +19123,9 @@ namespace ts {
const skipCaching = source.flags & TypeFlags.Union && (source as UnionType).types.length < 4 && !(target.flags & TypeFlags.Union) ||
target.flags & TypeFlags.Union && (target as UnionType).types.length < 4 && !(source.flags & TypeFlags.StructuredOrInstantiable);
let result = skipCaching ?
const result = skipCaching ?
unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) :
recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags);
// For certain combinations involving intersections and optional, excess, or mismatched properties we need
// an extra property check where the intersection is viewed as a single object. The following are motivating
// examples that all should be errors, but aren't without this extra property check:
//
// let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property
//
// declare let wrong: { a: { y: string } };
// let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type
//
// function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
// x = y; // Mismatched property in source intersection
// }
//
// We suppress recursive intersection property checks because they can generate lots of work when relating
// recursive intersections that are structurally similar but not exactly identical. See #37854.
if (result && !inPropertyCheck && (
target.flags & TypeFlags.Intersection && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source as IntersectionType).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) {
inPropertyCheck = true;
result &= recursiveTypeRelatedTo(source, target, reportErrors, IntersectionState.PropertyCheck, recursionFlags);
inPropertyCheck = false;
}
if (result) {
return result;
}
@@ -19481,8 +19529,7 @@ namespace ts {
if (overflow) {
return Ternary.False;
}
const keyIntersectionState = intersectionState | (inPropertyCheck ? IntersectionState.InPropertyCheck : 0);
const id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false);
const id = getRelationKey(source, target, intersectionState, relation, /*ingnoreConstraints*/ false);
const entry = relation.get(id);
if (entry !== undefined) {
if (reportErrors && entry & RelationComparisonResult.Failed && !(entry & RelationComparisonResult.Reported)) {
@@ -19512,7 +19559,7 @@ namespace ts {
// A key that starts with "*" is an indication that we have type references that reference constrained
// type parameters. For such keys we also check against the key we would have gotten if all type parameters
// were unconstrained.
const broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined;
const broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, intersectionState, relation, /*ignoreConstraints*/ true) : undefined;
for (let i = 0; i < maybeCount; i++) {
// If source and target are already being compared, consider them related with assumptions
if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) {
@@ -19600,7 +19647,7 @@ namespace ts {
function structuredTypeRelatedTo(source: Type, target: Type, reportErrors: boolean, intersectionState: IntersectionState): Ternary {
const saveErrorInfo = captureErrorCalculationState();
let result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState, saveErrorInfo);
if (!result && (source.flags & TypeFlags.Intersection || source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.Union)) {
if (relation !== identityRelation) {
// The combined constraint of an intersection type is the intersection of the constraints of
// the constituents. When an intersection type contains instantiable types with union type
// constraints, there are situations where we need to examine the combined constraint. One is
@@ -19614,10 +19661,34 @@ namespace ts {
// needs to have its constraint hoisted into an intersection with said type parameter, this way
// the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
// For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types: [source], !!(target.flags & TypeFlags.Union));
if (constraint && !(constraint.flags & TypeFlags.Never) && everyType(constraint, c => c !== source)) { // Skip comparison if expansion contains the source itself
// TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
if (!result && (source.flags & TypeFlags.Intersection || source.flags & TypeFlags.TypeParameter && target.flags & TypeFlags.Union)) {
const constraint = getEffectiveConstraintOfIntersection(source.flags & TypeFlags.Intersection ? (source as IntersectionType).types: [source], !!(target.flags & TypeFlags.Union));
if (constraint && everyType(constraint, c => c !== source)) { // Skip comparison if expansion contains the source itself
// TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
}
}
// For certain combinations involving intersections and optional, excess, or mismatched properties we need
// an extra property check where the intersection is viewed as a single object. The following are motivating
// examples that all should be errors, but aren't without this extra property check:
//
// let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property
//
// declare let wrong: { a: { y: string } };
// let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type
//
// function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
// x = y; // Mismatched property in source intersection
// }
//
// We suppress recursive intersection property checks because they can generate lots of work when relating
// recursive intersections that are structurally similar but not exactly identical. See #37854.
if (result && !inPropertyCheck && (
target.flags & TypeFlags.Intersection && !isGenericObjectType(target) && source.flags & (TypeFlags.Object | TypeFlags.Intersection) ||
isNonGenericObjectType(target) && !isArrayOrTupleType(target) && source.flags & TypeFlags.Intersection && getApparentType(source).flags & TypeFlags.StructuredType && !some((source as IntersectionType).types, t => !!(getObjectFlags(t) & ObjectFlags.NonInferrableType)))) {
inPropertyCheck = true;
result &= propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, IntersectionState.None);
inPropertyCheck = false;
}
}
if (result) {
@@ -19627,9 +19698,6 @@ namespace ts {
}
function structuredTypeRelatedToWorker(source: Type, target: Type, reportErrors: boolean, intersectionState: IntersectionState, saveErrorInfo: ReturnType<typeof captureErrorCalculationState>): Ternary {
if (intersectionState & IntersectionState.PropertyCheck) {
return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, IntersectionState.None);
}
let result: Ternary;
let originalErrorInfo: DiagnosticMessageChain | undefined;
let varianceCheckFailed = false;
@@ -19734,7 +19802,7 @@ namespace ts {
// with another type parameter unless one extends the other. (Remember: comparability is mostly bidirectional!)
let constraint = getConstraintOfTypeParameter(source);
if (constraint && hasNonCircularBaseConstraint(source)) {
while (constraint && constraint.flags & TypeFlags.TypeParameter) {
while (constraint && someType(constraint, c => !!(c.flags & TypeFlags.TypeParameter))) {
if (result = isRelatedTo(constraint, target, RecursionFlags.Source, /*reportErrors*/ false)) {
return result;
}
@@ -20399,7 +20467,7 @@ namespace ts {
return Ternary.False;
}
// When checking for comparability, be more lenient with optional properties.
if (!skipOptional && sourceProp.flags & SymbolFlags.Optional && !(targetProp.flags & SymbolFlags.Optional)) {
if (!skipOptional && sourceProp.flags & SymbolFlags.Optional && targetProp.flags & SymbolFlags.ClassMember && !(targetProp.flags & SymbolFlags.Optional)) {
// TypeScript 1.0 spec (April 2014): 3.8.3
// S is a subtype of a type T, and T is a supertype of S if ...
// S' and T are object types and, for each member M in T..
@@ -21562,8 +21630,7 @@ namespace ts {
}
function isUnitLikeType(type: Type): boolean {
return type.flags & TypeFlags.Intersection ? some((type as IntersectionType).types, isUnitType) :
!!(type.flags & TypeFlags.Unit);
return isUnitType(getBaseConstraintOrType(type));
}
function extractUnitType(type: Type) {
@@ -22495,7 +22562,7 @@ namespace ts {
}
function isMemberOfStringMapping(source: Type, target: Type): boolean {
if (target.flags & (TypeFlags.String | TypeFlags.AnyOrUnknown)) {
if (target.flags & (TypeFlags.String | TypeFlags.Any)) {
return true;
}
if (target.flags & TypeFlags.TemplateLiteral) {
@@ -24423,6 +24490,7 @@ namespace ts {
}
function getExplicitTypeOfSymbol(symbol: Symbol, diagnostic?: Diagnostic) {
symbol = resolveSymbol(symbol);
if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.Class | SymbolFlags.ValueModule)) {
return getTypeOfSymbol(symbol);
}
@@ -24462,7 +24530,7 @@ namespace ts {
switch (node.kind) {
case SyntaxKind.Identifier:
const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node as Identifier));
return getExplicitTypeOfSymbol(symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol, diagnostic);
return getExplicitTypeOfSymbol(symbol, diagnostic);
case SyntaxKind.ThisKeyword:
return getExplicitThisType(node);
case SyntaxKind.SuperKeyword:
@@ -24969,7 +25037,7 @@ namespace ts {
type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
}
else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) {
type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
type = narrowTypeBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
}
else {
if (strictNullChecks) {
@@ -25261,7 +25329,7 @@ namespace ts {
!!getApplicableIndexInfoForName(type, propName) || !assumeTrue;
}
function narrowByInKeyword(type: Type, nameType: StringLiteralType | NumberLiteralType | UniqueESSymbolType, assumeTrue: boolean) {
function narrowTypeByInKeyword(type: Type, nameType: StringLiteralType | NumberLiteralType | UniqueESSymbolType, assumeTrue: boolean) {
const name = getPropertyNameFromType(nameType);
const isKnownProperty = someType(type, t => isTypePresencePossible(t, name, /*assumeTrue*/ true));
if (isKnownProperty) {
@@ -25343,7 +25411,7 @@ namespace ts {
return getTypeWithFacts(type, assumeTrue ? TypeFacts.NEUndefined : TypeFacts.EQUndefined);
}
if (isMatchingReference(reference, target)) {
return narrowByInKeyword(type, leftType as StringLiteralType | NumberLiteralType | UniqueESSymbolType, assumeTrue);
return narrowTypeByInKeyword(type, leftType as StringLiteralType | NumberLiteralType | UniqueESSymbolType, assumeTrue);
}
}
break;
@@ -25543,7 +25611,7 @@ namespace ts {
neverType);
}
function narrowBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type {
function narrowTypeBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type {
const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
if (!witnesses) {
return type;
@@ -25965,15 +26033,15 @@ namespace ts {
}
function markAliasReferenced(symbol: Symbol, location: Node) {
if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol, SymbolFlags.Value)) {
const target = resolveAlias(symbol);
if (target.flags & SymbolFlags.Value) {
if (getAllSymbolFlags(target) & (SymbolFlags.Value | SymbolFlags.ExportValue)) {
// An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled
// (because the const enum value will not be inlined), or if (2) the alias is an export
// of a const enum declaration that will be preserved.
if (compilerOptions.isolatedModules ||
shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) ||
!isConstEnumOrConstEnumOnlyModule(target)
!isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))
) {
markAliasSymbolAsReferenced(symbol);
}
@@ -26222,7 +26290,7 @@ namespace ts {
// We only look for uninitialized variables in strict null checking mode, and only when we can analyze
// the entire control flow graph from the variable's declaration (i.e. when the flow container and
// declaration container are the same).
const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isBindingElement(declaration) ||
const assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) ||
type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (TypeFlags.AnyOrUnknown | TypeFlags.Void)) !== 0 ||
isInTypeQuery(node) || node.parent.kind === SyntaxKind.ExportSpecifier) ||
node.parent.kind === SyntaxKind.NonNullExpression ||
@@ -26252,6 +26320,13 @@ namespace ts {
return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
}
function isSameScopedBindingElement(node: Identifier, declaration: Declaration) {
if (isBindingElement(declaration)) {
const bindingElement = findAncestor(node, isBindingElement);
return bindingElement && getRootDeclaration(bindingElement) === getRootDeclaration(declaration);
}
}
function shouldMarkIdentifierAliasReferenced(node: Identifier): boolean {
const parent = node.parent;
if (parent) {
@@ -26632,13 +26707,16 @@ namespace ts {
const immediateContainer = getSuperContainer(node, /*stopOnFunctions*/ true);
let container = immediateContainer;
let needToCaptureLexicalThis = false;
let inAsyncFunction = false;
// adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
if (!isCallExpression) {
while (container && container.kind === SyntaxKind.ArrowFunction) {
if (hasSyntacticModifier(container, ModifierFlags.Async)) inAsyncFunction = true;
container = getSuperContainer(container, /*stopOnFunctions*/ true);
needToCaptureLexicalThis = languageVersion < ScriptTarget.ES2015;
}
if (container && hasSyntacticModifier(container, ModifierFlags.Async)) inAsyncFunction = true;
}
const canUseSuperExpression = isLegalUsageOfSuperExpression(container);
@@ -26750,12 +26828,12 @@ namespace ts {
// as a call expression cannot be used as the target of a destructuring assignment while a property access can.
//
// For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
if (container.kind === SyntaxKind.MethodDeclaration && hasSyntacticModifier(container, ModifierFlags.Async)) {
if (container.kind === SyntaxKind.MethodDeclaration && inAsyncFunction) {
if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) {
getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuperBinding;
getNodeLinks(container).flags |= NodeCheckFlags.MethodWithSuperPropertyAssignmentInAsync;
}
else {
getNodeLinks(container).flags |= NodeCheckFlags.AsyncMethodWithSuper;
getNodeLinks(container).flags |= NodeCheckFlags.MethodWithSuperPropertyAccessInAsync;
}
}
@@ -27532,9 +27610,10 @@ namespace ts {
function instantiateContextualType(contextualType: Type | undefined, node: Node, contextFlags: ContextFlags | undefined): Type | undefined {
if (contextualType && maybeTypeOfKind(contextualType, TypeFlags.Instantiable)) {
const inferenceContext = getInferenceContext(node);
// If no inferences have been made, nothing is gained from instantiating as type parameters
// would just be replaced with their defaults similar to the apparent type.
if (inferenceContext && contextFlags! & ContextFlags.Signature && some(inferenceContext.inferences, hasInferenceCandidates)) {
// If no inferences have been made, and none of the type parameters for which we are inferring
// specify default types, nothing is gained from instantiating as type parameters would just be
// replaced with their constraints similar to the apparent type.
if (inferenceContext && contextFlags! & ContextFlags.Signature && some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) {
// For contextual signatures we incorporate all inferences made so far, e.g. from return
// types as well as arguments to the left in a function call.
return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
@@ -32514,7 +32593,7 @@ namespace ts {
if (symbol && symbol.flags & SymbolFlags.Alias) {
symbol = resolveAlias(symbol);
}
return !!(symbol && (symbol.flags & SymbolFlags.Enum) && getEnumKind(symbol) === EnumKind.Literal);
return !!(symbol && (getAllSymbolFlags(symbol) & SymbolFlags.Enum) && getEnumKind(symbol) === EnumKind.Literal);
}
return false;
}
@@ -33241,7 +33320,17 @@ namespace ts {
function isExhaustiveSwitchStatement(node: SwitchStatement): boolean {
const links = getNodeLinks(node);
return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
if (links.isExhaustive === undefined) {
links.isExhaustive = 0; // Indicate resolution is in process
const exhaustive = computeExhaustiveSwitchStatement(node);
if (links.isExhaustive === 0) {
links.isExhaustive = exhaustive;
}
}
else if (links.isExhaustive === 0) {
links.isExhaustive = false; // Resolve circularity to false
}
return links.isExhaustive;
}
function computeExhaustiveSwitchStatement(node: SwitchStatement): boolean {
@@ -33250,7 +33339,7 @@ namespace ts {
if (!witnesses) {
return false;
}
const operandConstraint = getBaseConstraintOrType(getTypeOfExpression((node.expression as TypeOfExpression).expression));
const operandConstraint = getBaseConstraintOrType(checkExpressionCached((node.expression as TypeOfExpression).expression));
// Get the not-equal flags for all handled cases.
const notEqualFacts = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses);
if (operandConstraint.flags & TypeFlags.AnyOrUnknown) {
@@ -33260,7 +33349,7 @@ namespace ts {
// A missing not-equal flag indicates that the type wasn't handled by some case.
return !someType(operandConstraint, t => (getTypeFacts(t) & notEqualFacts) === notEqualFacts);
}
const type = getTypeOfExpression(node.expression);
const type = checkExpressionCached(node.expression);
if (!isLiteralType(type)) {
return false;
}
@@ -35145,6 +35234,10 @@ namespace ts {
return !!(info.candidates || info.contraCandidates);
}
function hasInferenceCandidatesOrDefault(info: InferenceInfo) {
return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter));
}
function hasOverlappingInferences(a: InferenceInfo[], b: InferenceInfo[]) {
for (let i = 0; i < a.length; i++) {
if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
@@ -36902,7 +36995,7 @@ namespace ts {
}
// primitives with a `{ then() }` won't be unwrapped/adopted.
if (allTypesAssignableToKind(type, TypeFlags.Primitive | TypeFlags.Never)) {
if (allTypesAssignableToKind(getBaseConstraintOrType(type), TypeFlags.Primitive | TypeFlags.Never)) {
return undefined;
}
@@ -36977,7 +37070,7 @@ namespace ts {
* Determines whether a type is an object with a callable `then` member.
*/
function isThenableType(type: Type): boolean {
if (allTypesAssignableToKind(type, TypeFlags.Primitive | TypeFlags.Never)) {
if (allTypesAssignableToKind(getBaseConstraintOrType(type), TypeFlags.Primitive | TypeFlags.Never)) {
// primitive types cannot be considered "thenable" since they are not objects.
return false;
}
@@ -37021,7 +37114,7 @@ namespace ts {
// We only need `Awaited<T>` if `T` is a type variable that has no base constraint, or the base constraint of `T` is `any`, `unknown`, `{}`, `object`,
// or is promise-like.
if (baseConstraint ?
baseConstraint.flags & TypeFlags.AnyOrUnknown || isEmptyObjectType(baseConstraint) || isThenableType(baseConstraint) :
baseConstraint.flags & TypeFlags.AnyOrUnknown || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) :
maybeTypeOfKind(type, TypeFlags.TypeVariable)) {
return true;
}
@@ -39370,7 +39463,18 @@ namespace ts {
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;
return errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
const suggestAwait =
// for (const x of Promise<...>) or [...Promise<...>]
!!getAwaitedTypeOfPromise(type)
// for (const x of AsyncIterable<...>)
|| (
!allowAsyncIterables &&
isForOfStatement(errorNode.parent) &&
errorNode.parent.expression === errorNode &&
getGlobalAsyncIterableType(/** reportErrors */ false) !== emptyGenericType &&
isTypeAssignableTo(type, getGlobalAsyncIterableType(/** reportErrors */ false)
));
return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type));
}
/**
@@ -40032,7 +40136,7 @@ namespace ts {
}
}
else {
forEach(jsdocParameters, ({ name }, index) => {
forEach(jsdocParameters, ({ name, isNameFirst }, index) => {
if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) {
return;
}
@@ -40042,7 +40146,9 @@ namespace ts {
}
}
else {
errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name));
if (!isNameFirst) {
errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name));
}
}
});
}
@@ -41318,18 +41424,6 @@ namespace ts {
if (isGlobalAugmentation) {
return;
}
const symbol = getSymbolOfNode(node);
if (symbol) {
// module augmentations cannot introduce new names on the top level scope of the module
// this is done it two steps
// 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
// 2. main check - report error if value declaration of the parent symbol is module augmentation)
let reportError = !(symbol.flags & SymbolFlags.Transient);
if (!reportError) {
// symbol should not originate in augmentation
reportError = !!symbol.parent?.declarations && isExternalModuleAugmentation(symbol.parent.declarations[0]);
}
}
break;
}
}
@@ -41444,11 +41538,12 @@ namespace ts {
return;
}
const targetFlags = getAllSymbolFlags(target);
const excludedMeanings =
(symbol.flags & (SymbolFlags.Value | SymbolFlags.ExportValue) ? SymbolFlags.Value : 0) |
(symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) |
(symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0);
if (target.flags & excludedMeanings) {
if (targetFlags & excludedMeanings) {
const message = node.kind === SyntaxKind.ExportSpecifier ?
Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
@@ -41459,7 +41554,7 @@ namespace ts {
&& !isTypeOnlyImportOrExportDeclaration(node)
&& !(node.flags & NodeFlags.Ambient)) {
const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol);
const isType = !(target.flags & SymbolFlags.Value);
const isType = !(targetFlags & SymbolFlags.Value);
if (isType || typeOnlyAlias) {
switch (node.kind) {
case SyntaxKind.ImportClause:
@@ -41637,14 +41732,15 @@ namespace ts {
if (node.moduleReference.kind !== SyntaxKind.ExternalModuleReference) {
const target = resolveAlias(getSymbolOfNode(node));
if (target !== unknownSymbol) {
if (target.flags & SymbolFlags.Value) {
const targetFlags = getAllSymbolFlags(target);
if (targetFlags & SymbolFlags.Value) {
// Target is a value symbol, check that it is not hidden by a local declaration with the same name
const moduleName = getFirstIdentifier(node.moduleReference);
if (!(resolveEntityName(moduleName, SymbolFlags.Value | SymbolFlags.Namespace)!.flags & SymbolFlags.Namespace)) {
error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName));
}
}
if (target.flags & SymbolFlags.Type) {
if (targetFlags & SymbolFlags.Type) {
checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0);
}
}
@@ -41795,7 +41891,7 @@ namespace ts {
markExportAsReferenced(node);
}
const target = symbol && (symbol.flags & SymbolFlags.Alias ? resolveAlias(symbol) : symbol);
if (!target || target === unknownSymbol || target.flags & SymbolFlags.Value) {
if (!target || getAllSymbolFlags(target) & SymbolFlags.Value) {
checkExpressionCached(node.propertyName || node.name);
}
}
@@ -41847,7 +41943,7 @@ namespace ts {
markAliasReferenced(sym, id);
// If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
const target = sym.flags & SymbolFlags.Alias ? resolveAlias(sym) : sym;
if (target === unknownSymbol || target.flags & SymbolFlags.Value) {
if (getAllSymbolFlags(target) & SymbolFlags.Value) {
// However if it is a value, we need to check it's being used correctly
checkExpressionCached(node.expression);
}
@@ -42583,27 +42679,6 @@ namespace ts {
getNameOfDeclaration(name.parent) === name;
}
function isTypeDeclaration(node: Node): node is TypeParameterDeclaration | ClassDeclaration | InterfaceDeclaration | TypeAliasDeclaration | JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag | EnumDeclaration | ImportClause | ImportSpecifier | ExportSpecifier {
switch (node.kind) {
case SyntaxKind.TypeParameter:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.JSDocTypedefTag:
case SyntaxKind.JSDocCallbackTag:
case SyntaxKind.JSDocEnumTag:
return true;
case SyntaxKind.ImportClause:
return (node as ImportClause).isTypeOnly;
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return (node as ImportSpecifier | ExportSpecifier).parent.parent.isTypeOnly;
default:
return false;
}
}
// True if the given identifier is part of a type reference
function isTypeReferenceIdentifier(node: EntityName): boolean {
while (node.parent.kind === SyntaxKind.QualifiedName) {
@@ -43305,7 +43380,7 @@ namespace ts {
function isValue(s: Symbol): boolean {
s = resolveSymbol(s);
return s && !!(s.flags & SymbolFlags.Value);
return s && !!(getAllSymbolFlags(s) & SymbolFlags.Value);
}
}
@@ -43361,7 +43436,7 @@ namespace ts {
// We should only get the declaration of an alias if there isn't a local value
// declaration for the symbol
if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !getTypeOnlyAliasDeclaration(symbol)) {
if (isNonLocalAlias(symbol, /*excludes*/ SymbolFlags.Value) && !getTypeOnlyAliasDeclaration(symbol, SymbolFlags.Value)) {
return getDeclarationOfAliasSymbol(symbol);
}
}
@@ -43458,7 +43533,7 @@ namespace ts {
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
const symbol = getSymbolOfNode(node);
return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
return !!symbol && isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol, SymbolFlags.Value);
case SyntaxKind.ExportDeclaration:
const exportClause = (node as ExportDeclaration).exportClause;
return !!exportClause && (
@@ -43494,7 +43569,7 @@ namespace ts {
}
// const enums and modules that contain only const enums are not considered values from the emit perspective
// unless 'preserveConstEnums' option is set to true
return !!(target.flags & SymbolFlags.Value) &&
return !!((getAllSymbolFlags(target) ?? -1) & SymbolFlags.Value) &&
(shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
}
@@ -43511,7 +43586,7 @@ namespace ts {
}
const target = getSymbolLinks(symbol!).aliasTarget; // TODO: GH#18217
if (target && getEffectiveModifierFlags(node) & ModifierFlags.Export &&
target.flags & SymbolFlags.Value &&
getAllSymbolFlags(target) & SymbolFlags.Value &&
(shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
// An `export import ... =` of a value symbol is always considered referenced
return true;
+18 -10
View File
@@ -436,9 +436,6 @@ namespace ts {
name: "listFilesOnly",
type: "boolean",
category: Diagnostics.Command_line_Options,
affectsSemanticDiagnostics: true,
affectsEmit: true,
affectsMultiFileEmitBuildInfo: true,
isCommandLineOnly: true,
description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing,
defaultValueDescription: false,
@@ -2411,7 +2408,8 @@ namespace ts {
return config;
}
function optionMapToObject(optionMap: ESMap<string, CompilerOptionsValue>): object {
/*@internal*/
export function optionMapToObject(optionMap: ESMap<string, CompilerOptionsValue>): object {
return {
...arrayFrom(optionMap.entries()).reduce((prev, cur) => ({ ...prev, [cur[0]]: cur[1] }), {}),
};
@@ -2464,7 +2462,8 @@ namespace ts {
});
}
function serializeCompilerOptions(
/* @internal */
export function serializeCompilerOptions(
options: CompilerOptions,
pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }
): ESMap<string, CompilerOptionsValue> {
@@ -2582,12 +2581,21 @@ namespace ts {
function writeConfigurations() {
// Filter applicable options to place in the file
const categorizedOptions = createMultiMap<CommandLineOption>();
const categorizedOptions = new Map<DiagnosticMessage, CommandLineOption[]>();
// Set allowed categories in order
categorizedOptions.set(Diagnostics.Projects, []);
categorizedOptions.set(Diagnostics.Language_and_Environment, []);
categorizedOptions.set(Diagnostics.Modules, []);
categorizedOptions.set(Diagnostics.JavaScript_Support, []);
categorizedOptions.set(Diagnostics.Emit, []);
categorizedOptions.set(Diagnostics.Interop_Constraints, []);
categorizedOptions.set(Diagnostics.Type_Checking, []);
categorizedOptions.set(Diagnostics.Completeness, []);
for (const option of optionDeclarations) {
const { category } = option;
if (isAllowedOptionForOutput(option)) {
categorizedOptions.add(getLocaleSpecificMessage(category!), option);
let listForCategory = categorizedOptions.get(option.category!);
if (!listForCategory) categorizedOptions.set(option.category!, listForCategory = []);
listForCategory.push(option);
}
}
@@ -2599,7 +2607,7 @@ namespace ts {
if (entries.length !== 0) {
entries.push({ value: "" });
}
entries.push({ value: `/* ${category} */` });
entries.push({ value: `/* ${getLocaleSpecificMessage(category)} */` });
for (const option of options) {
let optionName;
if (compilerOptionsMap.has(option.name)) {
+4 -2
View File
@@ -1937,8 +1937,10 @@ namespace ts {
return compareValues(a?.start, b?.start) || compareValues(a?.length, b?.length);
}
export function min<T>(a: T, b: T, compare: Comparer<T>): T {
return compare(a, b) === Comparison.LessThan ? a : b;
export function min<T>(items: readonly [T, ...T[]], compare: Comparer<T>): T;
export function min<T>(items: readonly T[], compare: Comparer<T>): T | undefined;
export function min<T>(items: readonly T[], compare: Comparer<T>): T | undefined {
return reduceLeft(items, (x, y) => compare(x, y) === Comparison.LessThan ? x : y);
}
/**
+24
View File
@@ -5414,6 +5414,22 @@
"category": "Message",
"code": 6401
},
"Resolving in {0} mode with conditions {1}.": {
"category": "Message",
"code": 6402
},
"Matched '{0}' condition '{1}'.": {
"category": "Message",
"code": 6403
},
"Using '{0}' subpath '{1}' with target '{2}'.": {
"category": "Message",
"code": 6404
},
"Saw non-matching condition '{0}'.": {
"category": "Message",
"code": 6405
},
"The expected type comes from property '{0}' which is declared here on type '{1}'": {
"category": "Message",
@@ -6687,6 +6703,14 @@
"category": "Message",
"code": 90058
},
"Export '{0}' from module '{1}'": {
"category": "Message",
"code": 90059
},
"Export all referenced locals": {
"category": "Message",
"code": 90060
},
"Convert function to an ES2015 class": {
"category": "Message",
+1 -3
View File
@@ -17,13 +17,11 @@ namespace ts {
* Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
*/
export function createBaseNodeFactory(): BaseNodeFactory {
// tslint:disable variable-name
let NodeConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let TokenConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let IdentifierConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let PrivateIdentifierConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos?: number, end?: number) => Node;
// tslint:enable variable-name
return {
createBaseSourceFileNode,
@@ -53,4 +51,4 @@ namespace ts {
return new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
}
}
}
}
+3 -1
View File
@@ -705,6 +705,8 @@ namespace ts {
// - The verb (`next`, `throw`, or `return` method) to delegate to the expression
// of a `yield*`.
// - The result of evaluating the verb delegated to the expression of a `yield*`.
// g A temporary variable that holds onto the generator object until the generator
// is started, allowing it to also act as the `suspendedStart` state.
//
// functions:
// verb(n) Creates a bound callback to the `step` function for opcode `n`.
@@ -750,7 +752,7 @@ namespace ts {
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
+5 -4
View File
@@ -874,7 +874,7 @@ namespace ts {
}
// @api
function createIdentifier(text: string, typeArguments?: readonly (TypeNode | TypeParameterDeclaration)[], originalKeywordKind?: SyntaxKind): Identifier {
function createIdentifier(text: string, typeArguments?: readonly (TypeNode | TypeParameterDeclaration)[], originalKeywordKind?: SyntaxKind, hasExtendedUnicodeEscape?: boolean): Identifier {
const node = createBaseIdentifier(text, originalKeywordKind);
if (typeArguments) {
// NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
@@ -883,6 +883,10 @@ namespace ts {
if (node.originalKeywordKind === SyntaxKind.AwaitKeyword) {
node.transformFlags |= TransformFlags.ContainsPossibleTopLevelAwait;
}
if (hasExtendedUnicodeEscape) {
node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
node.transformFlags |= TransformFlags.ContainsES2015;
}
return node;
}
@@ -6403,11 +6407,9 @@ namespace ts {
rawTextScanner.setText("`" + rawText + "`");
break;
case SyntaxKind.TemplateHead:
// tslint:disable-next-line no-invalid-template-strings
rawTextScanner.setText("`" + rawText + "${");
break;
case SyntaxKind.TemplateMiddle:
// tslint:disable-next-line no-invalid-template-strings
rawTextScanner.setText("}" + rawText + "${");
break;
case SyntaxKind.TemplateTail:
@@ -6836,7 +6838,6 @@ namespace ts {
return node;
}
// tslint:disable-next-line variable-name
let SourceMapSource: new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource;
/**

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