From 39d7919bd942b54cacf3e73ee4914d01a35d89f8 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 10:08:53 -0800 Subject: [PATCH 1/3] Set up self-hosted TypeScript linting Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CONTRIBUTING.md | 6 +- Herebyfile.mjs | 22 +- eslint.config.mjs | 119 ++ package-lock.json | 1691 ++++++++++++++++- package.json | 10 +- packages/typescript/eslint/lint.test.mjs | 49 + .../eslint/rules/argument-trivia.cjs | 206 ++ .../typescript/eslint/rules/debug-assert.cjs | 65 + .../typescript/eslint/rules/js-extensions.cjs | 67 + .../typescript/eslint/rules/jsdoc-format.cjs | 146 ++ .../no-array-mutating-method-expressions.cjs | 126 ++ .../eslint/rules/no-in-operator.cjs | 33 + .../typescript/eslint/rules/no-keywords.cjs | 117 ++ .../eslint/rules/only-arrow-functions.cjs | 91 + packages/typescript/eslint/rules/utils.cjs | 2 + packages/typescript/package.json | 2 +- packages/typescript/scripts/tsconfig.json | 4 + packages/vscode-typescript/package.json | 2 +- 18 files changed, 2666 insertions(+), 92 deletions(-) create mode 100644 eslint.config.mjs create mode 100644 packages/typescript/eslint/lint.test.mjs create mode 100644 packages/typescript/eslint/rules/argument-trivia.cjs create mode 100644 packages/typescript/eslint/rules/debug-assert.cjs create mode 100644 packages/typescript/eslint/rules/js-extensions.cjs create mode 100644 packages/typescript/eslint/rules/jsdoc-format.cjs create mode 100644 packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs create mode 100644 packages/typescript/eslint/rules/no-in-operator.cjs create mode 100644 packages/typescript/eslint/rules/no-keywords.cjs create mode 100644 packages/typescript/eslint/rules/only-arrow-functions.cjs create mode 100644 packages/typescript/eslint/rules/utils.cjs create mode 100644 packages/typescript/scripts/tsconfig.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d7d86c5bbe486..d321845fe8970 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -126,7 +126,8 @@ npx hereby build # Build the native compiler into built/local/tsc npx hereby test # Run compiler and language-service Go tests npx hereby test:all # Also run benchmarks, tools, and API tests npx hereby test:codegen # Run codegen tests without regenerating source outputs -npx hereby lint # Run custom golangci-lint for both Go modules +npx hereby lint # Lint both Go modules and the TypeScript package +npx hereby lint:typescript # Lint the TypeScript package using the local compiler npx hereby generate:go # Run the generators also exposed through go generate npx hereby generate # Regenerate all sources, assets, localization, and vendored files npx hereby format # Format Go, TypeScript, JSON, and YAML @@ -142,6 +143,9 @@ the pinned LSP model when its local cache is missing or stale. Use `generate:go` for the narrower scope of `go generate ./...` in the `tsc` module. Up-to-date generators emit no status messages. +TypeScript linting uses the experimental native typescript-eslint project service, +the local API build, and `built/local/tsc`. The lint tasks build these prerequisites. + `npx hereby build` runs `generate` before compiling; a separate generation step is not needed. The API and package build tasks share this prerequisite, and `build:watch` runs the full incremental generation suite before every rebuild. diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 4fd9348279da3..8b0cd09007853 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -1432,11 +1432,13 @@ const customLinterTool = createCachedTool({ export const lint = task({ name: "lint", - description: "Runs golangci-lint.", + description: "Runs Go and TypeScript linters.", + dependencies: [local, buildAPI], run: runLint, }); async function runLint() { + await runLintTypeScript(); const lintArgs = ["run"]; if (defaultGoBuildTags.length) { lintArgs.push("--build-tags", defaultGoBuildTags.join(",")); @@ -1450,6 +1452,22 @@ async function runLint() { await customLinterTool.run([...lintArgs, "--config", "../.golangci.yml"], { cwd: "./tools" }); } +async function runLintTypeScript() { + await run("node", ["--test", "packages/typescript/eslint/lint.test.mjs"]); + const args = ["packages/typescript/{src,test,scripts}/**/*.ts"]; + if (options.fix) { + args.push("--fix"); + } + await run("eslint", args); +} + +export const lintTypeScript = task({ + name: "lint:typescript", + description: "Lints TypeScript package sources with the local compiler.", + dependencies: [local, buildAPI], + run: runLintTypeScript, +}); + export const installTools = task({ name: "install-tools", description: "Installs optional tools for developing within the repo.", @@ -1512,7 +1530,7 @@ async function fixLineEndings() { export const validate = task({ name: "validate", description: "Generates, builds, tests, lints, and formats the repo. Pass --api to include API tests, or --all to include API and ancillary repository tests. Benchmarks are separate: test:benchmarks and test:benchmarks:api.", - dependencies: [build], + dependencies: [build, buildAPI], run: async () => { /** @type {{ name: string; error: unknown }[]} */ const failures = []; diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000000000..6cc6b8b73f120 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,119 @@ +import eslint from "@eslint/js"; +import regexpPlugin from "eslint-plugin-regexp"; +import globals from "globals"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import tseslint from "typescript-eslint"; + +const require = createRequire(import.meta.url); +const rulesDir = path.join(import.meta.dirname, "packages/typescript/eslint/rules"); +const rules = Object.fromEntries( + fs.readdirSync(rulesDir) + .filter(file => file.endsWith(".cjs") && file !== "utils.cjs") + .map(file => [file.slice(0, -4), require(path.join(rulesDir, file))]), +); + +export default tseslint.config( + { + ignores: [ + "**/node_modules/**", + "packages/typescript/dist/**", + "packages/typescript/vendor/**", + "packages/typescript/**/*.generated.ts", + "packages/typescript/src/api/sync/api.ts", + "packages/typescript/src/api/sync/types.ts", + "packages/typescript/test/sync/api.bench.ts", + "packages/typescript/test/sync/api.test.ts", + "packages/typescript/test/sync/astnav.test.ts", + "packages/typescript/test/generators/api.bench.ts", + ], + }, + { + files: ["packages/typescript/{src,test,scripts}/**/*.ts"], + extends: [ + eslint.configs.recommended, + ...tseslint.configs.recommended, + ...tseslint.configs.stylistic, + regexpPlugin.configs["flat/recommended"], + ], + plugins: { local: { rules } }, + languageOptions: { + globals: globals.node, + parserOptions: { + projectService: { EXPERIMENTAL_backend: "tsgo" }, + tsconfigRootDir: import.meta.dirname, + }, + }, + rules: { + "dot-notation": "error", + "eqeqeq": "error", + "no-caller": "error", + "no-constant-condition": ["error", { checkLoops: false }], + "no-eval": "error", + "no-extra-bind": "error", + "no-new-func": "error", + "no-new-wrappers": "error", + "no-return-await": "error", + "no-template-curly-in-string": "error", + "no-throw-literal": "error", + "no-undef-init": "error", + "no-var": "error", + "object-shorthand": "error", + "prefer-const": "error", + "prefer-object-spread": "error", + "unicode-bom": ["error", "never"], + "no-restricted-syntax": [ + "error", + { selector: "Literal[raw=null]", message: "Avoid using null; use undefined instead." }, + { selector: "TSNullKeyword", message: "Avoid using null; use undefined instead." }, + ], + "no-extra-boolean-cast": "off", + "no-case-declarations": "off", + "no-cond-assign": "off", + "no-control-regex": "off", + "no-inner-declarations": "off", + "@typescript-eslint/naming-convention": [ + "error", + { selector: "typeLike", format: ["PascalCase"], filter: { regex: "^(__String|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "interface", format: ["PascalCase"], custom: { regex: "^I[A-Z]", match: false }, filter: { regex: "^I(Arguments|TextWriter|O([A-Z][a-z]+[A-Za-z]*)?)$", match: false } }, + { selector: "variable", format: ["camelCase", "PascalCase", "UPPER_CASE"], leadingUnderscore: "allow", filter: { regex: "^(_{1,2}filename|_{1,2}dirname|_+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "function", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^[A-Za-z]+_[A-Za-z]+$", match: false } }, + { selector: "parameter", format: ["camelCase"], leadingUnderscore: "allow", filter: { regex: "^(_+|[A-Za-z]+_[A-Z][a-z]+)$", match: false } }, + { selector: "method", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "memberLike", format: ["camelCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "enumMember", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^[A-Za-z]+_[A-Za-z]+$", match: false } }, + { selector: "property", format: null }, + ], + "@typescript-eslint/unified-signatures": "error", + "no-unused-expressions": "off", + "@typescript-eslint/no-unused-expressions": ["error", { allowTernary: true }], + "@typescript-eslint/ban-ts-comment": "off", + "@typescript-eslint/class-literal-property-style": "off", + "@typescript-eslint/consistent-indexed-object-style": "off", + "@typescript-eslint/consistent-generic-constructors": "off", + "@typescript-eslint/no-duplicate-enum-values": "off", + "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-namespace": "off", + "@typescript-eslint/no-non-null-asserted-optional-chain": "off", + "@typescript-eslint/no-empty-object-type": "off", + "@typescript-eslint/no-explicit-any": "off", + "@typescript-eslint/no-require-imports": "off", + "@typescript-eslint/no-unused-vars": [ + "error", + { argsIgnorePattern: "^(_+$|_[^_])", varsIgnorePattern: "^(_+$|_[^_])" }, + ], + "@typescript-eslint/no-inferrable-types": "off", + "@typescript-eslint/prefer-optional-chain": "off", + "@typescript-eslint/no-unnecessary-type-assertion": "error", + "local/only-arrow-functions": ["error", { allowNamedFunctions: true, allowDeclarations: true }], + "local/argument-trivia": "error", + "local/no-in-operator": "error", + "local/debug-assert": "error", + "local/no-keywords": "error", + "local/jsdoc-format": "error", + "local/js-extensions": "error", + "local/no-array-mutating-method-expressions": "error", + }, + }, +); diff --git a/package-lock.json b/package-lock.json index e695517383412..844ba432de707 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,18 +14,26 @@ "devDependencies": { "@dprint/json": "^0.25.2", "@dprint/typescript": "^0.96.1", + "@eslint/js": "^9.39.5", "@jakebailey/dprint-plugin-gofumpt": "^0.0.20", "@types/node": "^22.20.5", + "@typescript-eslint/type-utils": "^8.73.0", + "@typescript-eslint/utils": "^8.73.0", + "@typescript/native": "file:./packages/typescript", "@unicode/unicode-15.1.0": "^2.1.0", "adm-zip": "^0.6.1", "binaryen": "^132.0.0", "chokidar": "^6.0.0", "dprint": "^0.64.3", "dprint-plugin-yaml": "^0.6.0", + "eslint": "^9.39.5", + "eslint-plugin-regexp": "^3.3.3", + "globals": "^17.14.0", "hereby": "^1.15.2", "tar": "^7.5.22", "tinyexec": "^1.3.1", - "typescript": "^6.0.3" + "typescript": "^6.0.3", + "typescript-eslint": "^8.73.0" }, "engines": { "node": ">=22.18" @@ -965,6 +973,278 @@ "node": ">=18" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha1-iRG9crLDZApUNgngQAuMTS5+fLY=", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.3.tgz", + "integrity": "sha512-R76UKbvsqI68DJJVTVyqFKqU98CN4+B+acxNfEA2IFarSzP0SjtKf/3+fFiXzTyv5Fj3PxLkGHe2wnVWWMxobQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.2", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.2.tgz", + "integrity": "sha1-8p4iBXrVMWzyODbO6aNMgf/8t+Y=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.5" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-array/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha1-6D46fj8wCzTLnYf2FfoMvzV2kO4=", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/config-array/node_modules/brace-expansion": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz", + "integrity": "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha1-WAyI+NVEXyvWqo88re+g3nn71p4=", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha1-G9AGzut+LlWyt3OrMY0wDhpmrto=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha1-dyJYIEE9lhdQnak0IZCiAZ54dhw=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.7", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.7.tgz", + "integrity": "sha1-dtPe3sSjDqMt95e/igCFwTEbcxY=", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.14.0", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.3.2", + "minimatch": "^3.1.5", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha1-6D46fj8wCzTLnYf2FfoMvzV2kO4=", + "dev": true, + "license": "MIT" + }, + "node_modules/@eslint/eslintrc/node_modules/brace-expansion": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz", + "integrity": "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha1-iY10E8Kbq89rr+Vvyt3thYrack4=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/eslintrc/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha1-WAyI+NVEXyvWqo88re+g3nn71p4=", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.5.tgz", + "integrity": "sha1-by+8/3VQDSKdU14KlJrhNHLIR4c=", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha1-biEmoTR+hqTe34cG7Gf/jhB+u60=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha1-l3nj/Zt+4zVxpXQ1z0M1oXlKbLI=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha1-qCcsoDsqz0kmcCIrIyC2xCG/3mA=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha1-j4AMzME/T4zTEW4tnAqUk52j4+0=", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha1-8qCfYgEjkLK/8/xvskjd7IwJoJA=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha1-r1smkaIrRL6EewyoFkHF+2rQFyw=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha1-wrnS43TuYsWG062+qHGZsdenpro=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", @@ -978,6 +1258,13 @@ "node": ">=18.0.0" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jakebailey/dprint-plugin-gofumpt": { "version": "0.0.20", "resolved": "https://registry.npmjs.org/@jakebailey/dprint-plugin-gofumpt/-/dprint-plugin-gofumpt-0.0.20.tgz", @@ -1530,6 +1817,20 @@ "node": ">=20.0.0" } }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha1-WWoXRyM2lNUPatinhp/Lb1bPWEE=", + "dev": true, + "license": "MIT" + }, "node_modules/@types/node": { "version": "22.20.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", @@ -1547,107 +1848,377 @@ "dev": true, "license": "MIT" }, - "node_modules/@typescript/bundled-typescript": { - "name": "typescript", - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", - "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.73.0.tgz", + "integrity": "sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==", "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc" + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/type-utils": "8.73.0", + "@typescript-eslint/utils": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, - "optionalDependencies": { - "@typescript/typescript-aix-ppc64": "7.0.2", - "@typescript/typescript-darwin-arm64": "7.0.2", - "@typescript/typescript-darwin-x64": "7.0.2", - "@typescript/typescript-freebsd-arm64": "7.0.2", - "@typescript/typescript-freebsd-x64": "7.0.2", - "@typescript/typescript-linux-arm": "7.0.2", - "@typescript/typescript-linux-arm64": "7.0.2", - "@typescript/typescript-linux-loong64": "7.0.2", - "@typescript/typescript-linux-mips64el": "7.0.2", - "@typescript/typescript-linux-ppc64": "7.0.2", - "@typescript/typescript-linux-riscv64": "7.0.2", - "@typescript/typescript-linux-s390x": "7.0.2", - "@typescript/typescript-linux-x64": "7.0.2", - "@typescript/typescript-netbsd-arm64": "7.0.2", - "@typescript/typescript-netbsd-x64": "7.0.2", - "@typescript/typescript-openbsd-arm64": "7.0.2", - "@typescript/typescript-openbsd-x64": "7.0.2", - "@typescript/typescript-sunos-x64": "7.0.2", - "@typescript/typescript-win32-arm64": "7.0.2", - "@typescript/typescript-win32-x64": "7.0.2" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.73.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript": { - "resolved": "packages/typescript", - "link": true - }, - "node_modules/@typescript/typescript-aix-ppc64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", - "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", - "cpu": [ - "ppc64" - ], + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", + "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "aix" - ], + "license": "MIT", "engines": { - "node": ">=16.20.0" + "node": ">= 4" } }, - "node_modules/@typescript/typescript-darwin-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", - "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/parser": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz", + "integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", + "debug": "^4.4.3" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-darwin-x64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", - "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", - "cpu": [ - "x64" - ], + "node_modules/@typescript-eslint/project-service": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz", + "integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==", "dev": true, - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.73.0", + "@typescript-eslint/types": "^8.73.0", + "debug": "^4.4.3" + }, "engines": { - "node": ">=16.20.0" + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" } }, - "node_modules/@typescript/typescript-freebsd-arm64": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", - "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", - "cpu": [ - "arm64" - ], + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz", + "integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==", "dev": true, - "license": "Apache-2.0", - "optional": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz", + "integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.73.0.tgz", + "integrity": "sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/utils": "8.73.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz", + "integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz", + "integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.73.0", + "@typescript-eslint/tsconfig-utils": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/visitor-keys": "8.73.0", + "debug": "^4.4.3", + "minimatch": "^11.0.1", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev", + "typescript": ">=4.8.4 <6.1.0" + }, + "peerDependenciesMeta": { + "@typescript/native": { + "optional": true + } + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.73.0.tgz", + "integrity": "sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.73.0", + "@typescript-eslint/types": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz", + "integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.73.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha1-njyUiWl4JNLUzjqK0SYo+R6fWb4=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@typescript/bundled-typescript": { + "name": "typescript", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/@typescript/native": { + "resolved": "packages/typescript", + "link": true + }, + "node_modules/@typescript/typescript": { + "resolved": "packages/typescript", + "link": true + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, "os": [ "freebsd" ], @@ -2176,6 +2747,29 @@ "vscode": "^1.88.0" } }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha1-ftW7VZCLOy8bxVxq8WU7rafweTc=", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, "node_modules/adm-zip": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz", @@ -2196,6 +2790,23 @@ "node": ">= 14" } }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha1-B+mCx0YmFnqnoklcU4F4ktcTlJI=", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -2222,6 +2833,13 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha1-JG9Q88p4oyQPbJl+ipvR6sSeSzg=", + "dev": true, + "license": "Python-2.0" + }, "node_modules/azure-devops-node-api": { "version": "12.5.0", "resolved": "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-12.5.0.tgz", @@ -2359,6 +2977,33 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha1-s2MKvYlDQy9Us/BRkjjjPNffL3M=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha1-qsTit3NKdAhnrrFr8CqtVWoeegE=", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, "node_modules/chokidar": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-6.0.0.tgz", @@ -2440,6 +3085,38 @@ "node": ">=18" } }, + "node_modules/comment-parser": { + "version": "1.4.9", + "resolved": "https://registry.npmjs.org/comment-parser/-/comment-parser-1.4.9.tgz", + "integrity": "sha1-2zyAP+UAU2FEIO6JEF31jcp+Fd0=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha1-ilj+ePANzXDDcEUXWd+/rwPo7p8=", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2458,6 +3135,13 @@ } } }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha1-pvLc5hL63S7x9Rm3NVHxfoUZmDE=", + "dev": true, + "license": "MIT" + }, "node_modules/default-browser": { "version": "5.5.1", "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.1.tgz", @@ -2687,6 +3371,273 @@ "node": ">=6" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha1-FLqDpdNz49MR5a/KKc9b+tllvzQ=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.5", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.5.tgz", + "integrity": "sha1-Kk48iw91MZbvrpQ8j/qocw/Go/o=", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.2", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.6", + "@eslint/js": "9.39.5", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-regexp": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/eslint-plugin-regexp/-/eslint-plugin-regexp-3.3.3.tgz", + "integrity": "sha512-bIpFf1uL9AB6MY5cDUXL2lrfuBA+/WLc1AwC+56OsHWo93zoKQ4EcAQ+wsOxq5ozLC9xfTYAb4Si+0w0Ll1hYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.2.0", + "@eslint-community/regexpp": "^4.11.0", + "comment-parser": "^1.4.0", + "jsdoc-type-pratt-parser": "^9.0.0", + "refa": "^0.12.1", + "regexp-ast-analysis": "^0.7.1", + "scslre": "^0.3.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "peerDependencies": { + "eslint": ">=9.38.0" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha1-iOZGogf61hQ2/6OetQUUcgBlXII=", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha1-DNcv6FUOPC6uFWqWpN3c0cisWAA=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha1-6D46fj8wCzTLnYf2FfoMvzV2kO4=", + "dev": true, + "license": "MIT" + }, + "node_modules/eslint/node_modules/brace-expansion": { + "version": "1.1.22", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.22.tgz", + "integrity": "sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/eslint/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha1-TP6mD+fdCtjoFuHtAmwdUlG1EsE=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha1-WAyI+NVEXyvWqo88re+g3nn71p4=", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha1-1U9JSdRikAWh+haNk3w/8ffiqDc=", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree/node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha1-TP6mD+fdCtjoFuHtAmwdUlG1EsE=", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha1-CNBI8mHw3e21uulfRoCUY9nJSW0=", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha1-eteWTWeauyi+5yzsY3WLHF0smSE=", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha1-LupSkHAvJquP5TcDcP+GyWXSESM=", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha1-dNLrTeC42hKTcRkQ1Qd1ubcQ72Q=", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha1-On1WtVnWy8PrUSMlJE5hmmXGxSU=", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha1-h0v2nG9ATCtdmcSBNBOZ/VWJJjM=", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true, + "license": "MIT" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -2705,6 +3656,57 @@ } } }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha1-d4e93PETG/+5JjbGlFe7wO3W2B8=", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha1-TJKBnstwg1YeT0okCoa+UZj1Nvw=", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha1-Ds45/LFO4BL0sEEL0z3ZwfAREnw=", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha1-ruyipQYwPwzuYcWebJ8qiNLyn8Y=", + "dev": true, + "license": "ISC" + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -2764,6 +3766,32 @@ "node": ">= 0.4" } }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha1-bSN9mQg5UMeSkPJMdkKj3poo+eM=", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.14.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", + "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -2784,6 +3812,16 @@ "dev": true, "license": "ISC" }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha1-lEdx/ZyByBJlxNaUGGDaBrtZR5s=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/has-symbols": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", @@ -2864,6 +3902,43 @@ "node": ">= 14" } }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha1-PNQOcp82Q/2HywTlC/DrcivFlvU=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha1-nOy1ZQPAraHydB271lRuSxO1fM8=", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, "node_modules/is-docker": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", @@ -2880,6 +3955,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -2887,7 +3972,20 @@ "dev": true, "license": "MIT", "engines": { - "node": ">=8" + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha1-ZPYeQsu7LuwgcanawLKLoeZdUIQ=", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" } }, "node_modules/is-in-ssh": { @@ -2938,6 +4036,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true, + "license": "ISC" + }, "node_modules/istextorbinary": { "version": "9.5.0", "resolved": "https://registry.npmjs.org/istextorbinary/-/istextorbinary-9.5.0.tgz", @@ -2956,6 +4061,63 @@ "url": "https://bevry.me/fund" } }, + "node_modules/js-yaml": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha1-jkT7FKJkPFlya7FXh7XxUSyz0/s=", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsdoc-type-pratt-parser": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-9.5.0.tgz", + "integrity": "sha512-Qu/AuBJocEUhxq187P4Ud7xGBHB+NhtrclSrS7Utkr6uNeeh8BrZ5+Ax/AGe8VXQLGY+4oYgbUp04hY8iGsIWA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.9" + }, + "engines": { + "node": "^22.22.2 || >=24.15.0" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha1-kziAKjDTtmBfvgYT4JQAjKjAWhM=", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha1-afaofZUTq4u4/mO9sJecRI5oRmA=", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true, + "license": "MIT" + }, "node_modules/jsonc-parser": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", @@ -3009,6 +4171,46 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha1-qHmpnilFL5QkOfKkBeOvizHU3pM=", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha1-rkViwAdHO5MqYgDUAyaN0v/8at4=", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha1-VTIeswn+u8WcSAHZMackUqaB0oY=", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -3051,6 +4253,13 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha1-VYqlO0O2YeGSWgr9+japoQhf5Xo=", + "dev": true, + "license": "MIT" + }, "node_modules/lodash.once": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", @@ -3170,6 +4379,13 @@ "resolved": "packages/vscode-typescript", "link": true }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true, + "license": "MIT" + }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -3204,6 +4420,69 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha1-fqHBpdkddk+yghOciP4R4YKjpzQ=", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha1-4drMvnjQ0TiMoYxk/qOOPlfjcGs=", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha1-g8gxXGeFAF470CGDlBHJ4RDm2DQ=", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha1-aR0nCeeMefrjoVZiJFLQB2LKqqI=", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/parse5": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz", @@ -3217,6 +4496,26 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha1-UTvb4tO5XXdi6METfvoZXGxhtbM=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha1-WB9q3mWMu6ZaDTOA3ndTKVBU83U=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -3279,6 +4578,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha1-3rxkidem5rDnYRiIzsiAM30xY5Y=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/proper-lockfile": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", @@ -3291,6 +4600,16 @@ "signal-exit": "^3.0.2" } }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha1-AnQi4vrsCyXhVJw+G9gwm5EztuU=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/qs": { "version": "6.17.1", "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", @@ -3335,6 +4654,33 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/refa": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/refa/-/refa-0.12.1.tgz", + "integrity": "sha1-2sE8R4LcIra65szoGiuGOIjqOcY=", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.8.0" + }, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/regexp-ast-analysis": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/regexp-ast-analysis/-/regexp-ast-analysis-0.7.1.tgz", + "integrity": "sha1-wOJMsqkPbq3Uy6q6EpMX4p0pxII=", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.8.0", + "refa": "^0.12.1" + }, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -3345,6 +4691,16 @@ "node": ">=0.10.0" } }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha1-SrzYUq0y3Xuqv+m0DgCjbbXzkuY=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", @@ -3399,6 +4755,21 @@ "node": ">=11.0.0" } }, + "node_modules/scslre": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/scslre/-/scslre-0.3.0.tgz", + "integrity": "sha1-wyEem/xVR/yGseq6o07RplcGAVU=", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.8.0", + "refa": "^0.12.0", + "regexp-ast-analysis": "^0.7.0" + }, + "engines": { + "node": "^14.0.0 || >=16.0.0" + } + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -3411,6 +4782,29 @@ "node": ">=10" } }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha1-zNCvT4g1+9wmW4JGGq8MNmY/NOo=", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha1-rhbxZE2HPsrYQ7AwexQzYtTEIXI=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/side-channel": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", @@ -3522,6 +4916,19 @@ "node": ">=8" } }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha1-MfEoGzgyYwQ0gxwxDAHMzajL4AY=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/structured-source": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/structured-source/-/structured-source-4.0.0.tgz", @@ -3532,6 +4939,19 @@ "boundary": "^2.0.0" } }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha1-G33NyzK4E4gBs+R4umpRyqiWSNo=", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/tar": { "version": "7.5.22", "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", @@ -3611,6 +5031,19 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha1-Ss1KFV4ic0mQpe0f6el/ETvLN8E=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, "node_modules/tslib": { "version": "2.9.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", @@ -3627,6 +5060,19 @@ "node": ">=0.6.11 <=0.7.0 || >=0.7.3" } }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha1-B7ggO/pwVsBlcFDjzNLDdzC6uPE=", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/typed-rest-client": { "version": "1.8.11", "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.11.tgz", @@ -3653,6 +5099,30 @@ "node": ">=14.17" } }, + "node_modules/typescript-eslint": { + "version": "8.73.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.73.0.tgz", + "integrity": "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.73.0", + "@typescript-eslint/parser": "8.73.0", + "@typescript-eslint/typescript-estree": "8.73.0", + "@typescript-eslint/utils": "8.73.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, "node_modules/underscore": { "version": "1.13.8", "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz", @@ -3667,6 +5137,16 @@ "dev": true, "license": "MIT" }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha1-mxpSWVIlhZ5V9mnZKPiMbFfyp34=", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, "node_modules/url-join": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", @@ -3749,6 +5229,32 @@ "resolved": "packages/vscode-typescript-nightly", "link": true }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha1-fGqN0KY2oDJ+ELWckobu6T8/UbE=", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha1-0sRcbdT7zmIaZvE2y+Mor9BBCzQ=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/wrap-ansi": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", @@ -3880,9 +5386,22 @@ "buffer-crc32": "~0.2.3" } }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha1-ApTrPe4FAo0x7hpfosVWpqrxChs=", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "packages/typescript": { "name": "@typescript/typescript", - "version": "0.0.0", + "version": "7.1.0", "license": "Apache-2.0", "bin": { "tsc": "bin/tsc" @@ -3913,7 +5432,7 @@ "devDependencies": { "@types/vscode": "~1.125.0", "@typescript/bundled-typescript": "npm:typescript@7.0.2", - "@typescript/typescript": "0.0.0", + "@typescript/typescript": "7.1.0", "@vscode/vsce": "4.1.0", "@vscode/wasm-wasi": "^1.0.2", "esbuild": "^0.28.2" diff --git a/package.json b/package.json index 54f0c1c7fdb94..6a0b3d8b80b8b 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,11 @@ "devDependencies": { "@dprint/json": "^0.25.2", "@dprint/typescript": "^0.96.1", + "@eslint/js": "^9.39.5", "@jakebailey/dprint-plugin-gofumpt": "^0.0.20", + "@typescript-eslint/type-utils": "^8.73.0", + "@typescript-eslint/utils": "^8.73.0", + "@typescript/native": "file:./packages/typescript", "@types/node": "^22.20.5", "@unicode/unicode-15.1.0": "^2.1.0", "adm-zip": "^0.6.1", @@ -34,10 +38,14 @@ "chokidar": "^6.0.0", "dprint": "^0.64.3", "dprint-plugin-yaml": "^0.6.0", + "eslint": "^9.39.5", + "eslint-plugin-regexp": "^3.3.3", + "globals": "^17.14.0", "hereby": "^1.15.2", "tar": "^7.5.22", "tinyexec": "^1.3.1", - "typescript": "^6.0.3" + "typescript": "^6.0.3", + "typescript-eslint": "^8.73.0" }, "overrides": { "@microsoft/applicationinsights-web-basic": "3.3.11", diff --git a/packages/typescript/eslint/lint.test.mjs b/packages/typescript/eslint/lint.test.mjs new file mode 100644 index 0000000000000..03d594034b844 --- /dev/null +++ b/packages/typescript/eslint/lint.test.mjs @@ -0,0 +1,49 @@ +import { API } from "@typescript/native/sync"; +import { ESLint } from "eslint"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { test } from "node:test"; +import getExePath from "../lib/getExePath.js"; + +test("lint uses the local native API for typed custom rules", async () => { + const root = path.resolve(import.meta.dirname, "../../.."); + const executable = getExePath({ + fs: process.getBuiltinModule("node:fs"), + module: process.getBuiltinModule("node:module"), + path: process.getBuiltinModule("node:path"), + url: process.getBuiltinModule("node:url"), + }); + assert.equal(executable, path.join(root, "built/local", process.platform === "win32" ? "tsc.exe" : "tsc")); + + const descriptor = Object.getOwnPropertyDescriptor(API.prototype, "createSnapshot"); + assert.ok(descriptor?.get); + let snapshots = 0; + Object.defineProperty(API.prototype, "createSnapshot", { + ...descriptor, + get() { + snapshots++; + return descriptor.get.call(this); + }, + }); + try { + const eslint = new ESLint({ cwd: root }); + const filePath = "packages/typescript/src/internal/lint-probe.ts"; + const [result] = await eslint.lintText( + "function check(flag: boolean) { return flag; }\ncheck(true);\nconst xs: number[] = [1];\nconst ys = xs.sort();\n", + { filePath }, + ); + assert.ok(snapshots > 0, "lint must create a native snapshot"); + const argument = result.messages.find(message => message.ruleId === "local/argument-trivia"); + assert.equal(argument?.fix?.text, "/*flag*/ "); + assert.ok(result.messages.some(message => message.ruleId === "local/no-array-mutating-method-expressions")); + + const [imports] = await eslint.lintText( + 'import "./missing";\nimport "./present.ts";\nimport "./present.js";\nimport "./present.json";\n', + { filePath }, + ); + assert.equal(imports.messages.filter(message => message.ruleId === "local/js-extensions").length, 1); + } + finally { + Object.defineProperty(API.prototype, "createSnapshot", descriptor); + } +}); diff --git a/packages/typescript/eslint/rules/argument-trivia.cjs b/packages/typescript/eslint/rules/argument-trivia.cjs new file mode 100644 index 0000000000000..8eec22103db08 --- /dev/null +++ b/packages/typescript/eslint/rules/argument-trivia.cjs @@ -0,0 +1,206 @@ +const { AST_NODE_TYPES, ESLintUtils } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); +const ts = require("typescript"); + +/** + * @import { TSESTree } from "@typescript-eslint/utils" + * @typedef {TSESTree.CallExpression | TSESTree.NewExpression} CallOrNewExpression + */ +void 0; + +const unset = Symbol(); +/** + * @template T + * @param {() => T} fn + * @returns {() => T} + */ +function memoize(fn) { + /** @type {T | typeof unset} */ + let value = unset; + return () => { + if (value === unset) { + value = fn(); + } + return value; + }; +} + +module.exports = createRule({ + name: "argument-trivia", + meta: { + docs: { + description: ``, + }, + messages: { + argumentTriviaArgumentError: `Tag argument with parameter name`, + argumentTriviaArgumentSpaceError: `There should be 1 space between an argument and its comment`, + argumentTriviaArgumentNameError: `Argument name "{{ got }}" does not match expected name "{{ want }}"`, + }, + schema: [], + type: "problem", + fixable: "code", + }, + defaultOptions: [], + + create(context) { + const sourceCode = context.sourceCode; + const sourceCodeText = sourceCode.getText(); + + /** @type {(name: string) => boolean} */ + const isSetOrAssert = name => name.startsWith("set") || name.startsWith("assert"); + /** @type {(node: TSESTree.Node) => boolean} */ + const isTrivia = node => { + if (node.type === AST_NODE_TYPES.Identifier) { + return node.name === "undefined"; + } + + if (node.type === AST_NODE_TYPES.Literal) { + // eslint-disable-next-line no-restricted-syntax + return node.value === null || node.value === true || node.value === false; + } + + return false; + }; + + /** @type {(node: CallOrNewExpression) => boolean} */ + const shouldIgnoreCalledExpression = node => { + if (node.callee && node.callee.type === AST_NODE_TYPES.MemberExpression) { + const methodName = node.callee.property.type === AST_NODE_TYPES.Identifier + ? node.callee.property.name + : ""; + + if (isSetOrAssert(methodName)) { + return true; + } + + switch (methodName) { + case "apply": + case "call": + case "equal": + case "stringify": + case "push": + return true; + } + + return false; + } + + if (node.callee && node.callee.type === AST_NODE_TYPES.Identifier) { + const functionName = node.callee.name; + + if (isSetOrAssert(functionName)) { + return true; + } + + switch (functionName) { + case "contains": + return true; + } + + return false; + } + + return false; + }; + + /** @type {(node: TSESTree.Node, i: number, getSignature: () => ts.Signature | undefined) => void} */ + const checkArg = (node, i, getSignature) => { + if (!isTrivia(node)) { + return; + } + + const getExpectedName = memoize(() => { + const signature = getSignature(); + if (signature) { + const expectedName = signature.parameters[i]?.escapedName; + if (expectedName) { + const name = ts.unescapeLeadingUnderscores(expectedName); + // If a parameter is unused, we prepend an underscore. Ignore this + // so that we can switch between used and unused without modifying code, + // requiring that arugments are tagged with the non-underscored name. + return name.startsWith("_") ? name.slice(1) : name; + } + } + return undefined; + }); + + const comments = sourceCode.getCommentsBefore(node); + /** @type {TSESTree.Comment | undefined} */ + const comment = comments[comments.length - 1]; + + if (!comment || comment.type !== "Block") { + const expectedName = getExpectedName(); + if (expectedName) { + context.report({ + messageId: "argumentTriviaArgumentError", + node, + fix: fixer => { + return fixer.insertTextBefore(node, `/*${expectedName}*/ `); + }, + }); + } + else { + context.report({ messageId: "argumentTriviaArgumentError", node }); + } + return; + } + + const argRangeStart = node.range[0]; + const commentRangeEnd = comment.range[1]; + const expectedName = getExpectedName(); + if (expectedName) { + const got = comment.value; + if (got !== expectedName) { + context.report({ + messageId: "argumentTriviaArgumentNameError", + data: { got, want: expectedName }, + node: comment, + fix: fixer => { + return fixer.replaceText(comment, `/*${expectedName}*/`); + }, + }); + return; + } + } + + const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).includes("\n"); + if (argRangeStart !== commentRangeEnd + 1 && !hasNewLine) { + // TODO(jakebailey): range should be whitespace + context.report({ + messageId: "argumentTriviaArgumentSpaceError", + node, + fix: fixer => { + return fixer.replaceTextRange([commentRangeEnd, argRangeStart], " "); + }, + }); + } + }; + + /** @type {(node: CallOrNewExpression) => void} */ + const checkArgumentTrivia = node => { + if (shouldIgnoreCalledExpression(node)) { + return; + } + + const getSignature = memoize(() => { + const parserServices = ESLintUtils.getParserServices(context, /*allowWithoutFullTypeInformation*/ true); + if (parserServices.program) { + const checker = parserServices.program.getTypeChecker(); + const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node); + return checker.getResolvedSignature(tsNode); + } + return undefined; + }); + + for (let i = 0; i < node.arguments.length; i++) { + const arg = node.arguments[i]; + checkArg(arg, i, getSignature); + } + }; + + return { + CallExpression: checkArgumentTrivia, + NewExpression: checkArgumentTrivia, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/debug-assert.cjs b/packages/typescript/eslint/rules/debug-assert.cjs new file mode 100644 index 0000000000000..4938d9f35d22c --- /dev/null +++ b/packages/typescript/eslint/rules/debug-assert.cjs @@ -0,0 +1,65 @@ +const { AST_NODE_TYPES } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); + +/** @import { TSESTree } from "@typescript-eslint/utils" */ +void 0; + +module.exports = createRule({ + name: "debug-assert", + meta: { + docs: { + description: ``, + }, + messages: { + secondArgumentDebugAssertError: `Second argument to 'Debug.assert' should be a string literal`, + thirdArgumentDebugAssertError: `Third argument to 'Debug.assert' should be a string literal or arrow function`, + }, + schema: [], + type: "problem", + }, + defaultOptions: [], + + create(context) { + /** @type {(node: TSESTree.Node) => boolean} */ + const isArrowFunction = node => node.type === AST_NODE_TYPES.ArrowFunctionExpression; + /** @type {(node: TSESTree.Node) => boolean} */ + const isStringLiteral = node => ( + (node.type === AST_NODE_TYPES.Literal && typeof node.value === "string") || node.type === AST_NODE_TYPES.TemplateLiteral + ); + + /** @type {(node: TSESTree.MemberExpression) => boolean} */ + const isDebugAssert = node => ( + node.object.type === AST_NODE_TYPES.Identifier + && node.object.name === "Debug" + && node.property.type === AST_NODE_TYPES.Identifier + && node.property.name === "assert" + ); + + /** @type {(node: TSESTree.CallExpression) => void} */ + const checkDebugAssert = node => { + const args = node.arguments; + const argsLen = args.length; + if (!(node.callee.type === AST_NODE_TYPES.MemberExpression && isDebugAssert(node.callee)) || argsLen < 2) { + return; + } + + const message1Node = args[1]; + if (message1Node && !isStringLiteral(message1Node)) { + context.report({ messageId: "secondArgumentDebugAssertError", node: message1Node }); + } + + if (argsLen !== 3) { + return; + } + + const message2Node = args[2]; + if (message2Node && (!isStringLiteral(message2Node) && !isArrowFunction(message2Node))) { + context.report({ messageId: "thirdArgumentDebugAssertError", node: message2Node }); + } + }; + + return { + CallExpression: checkDebugAssert, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/js-extensions.cjs b/packages/typescript/eslint/rules/js-extensions.cjs new file mode 100644 index 0000000000000..a2defceddfe21 --- /dev/null +++ b/packages/typescript/eslint/rules/js-extensions.cjs @@ -0,0 +1,67 @@ +const { createRule } = require("./utils.cjs"); + +/** @import { TSESTree } from "@typescript-eslint/utils" */ +void 0; + +module.exports = createRule({ + name: "js-extensions", + meta: { + docs: { + description: ``, + }, + messages: { + missingJsExtension: `This relative module reference is missing a TypeScript, JavaScript, or JSON extension`, + }, + schema: [], + type: "suggestion", + }, + defaultOptions: [], + + create(context) { + /** @type {( + * node: + * | TSESTree.ImportDeclaration + * | TSESTree.ExportAllDeclaration + * | TSESTree.ExportNamedDeclaration + * | TSESTree.TSImportEqualsDeclaration + * | TSESTree.TSModuleDeclaration + * ) => void} + */ + const check = node => { + let source; + if (node.type === "TSImportEqualsDeclaration") { + const moduleReference = node.moduleReference; + if ( + moduleReference.type === "TSExternalModuleReference" + && moduleReference.expression.type === "Literal" + && typeof moduleReference.expression.value === "string" + ) { + source = moduleReference.expression; + } + } + else if (node.type === "TSModuleDeclaration") { + if (node.kind === "module" && node.id.type === "Literal") { + source = node.id; + } + } + else { + source = node.source; + } + + if (source?.value.startsWith(".") && !/\.(?:[cm]?[jt]s|json)$/.test(source.value)) { + context.report({ + messageId: "missingJsExtension", + node: source, + }); + } + }; + + return { + ImportDeclaration: check, + ExportAllDeclaration: check, + ExportNamedDeclaration: check, + TSImportEqualsDeclaration: check, + TSModuleDeclaration: check, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/jsdoc-format.cjs b/packages/typescript/eslint/rules/jsdoc-format.cjs new file mode 100644 index 0000000000000..735e9c69e8888 --- /dev/null +++ b/packages/typescript/eslint/rules/jsdoc-format.cjs @@ -0,0 +1,146 @@ +const { createRule } = require("./utils.cjs"); + +/** @import { TSESTree } from "@typescript-eslint/utils" */ +void 0; + +module.exports = createRule({ + name: "jsdoc-format", + meta: { + docs: { + description: ``, + }, + messages: { + internalCommentInNonJSDocError: `@internal should not appear in non-JSDoc comment for declaration.`, + internalCommentNotLastError: `@internal should only appear in final JSDoc comment for declaration.`, + multipleJSDocError: `Declaration has multiple JSDoc comments.`, + internalCommentOnParameterProperty: `@internal cannot appear on a JSDoc comment; use a declared property and an assignment in the constructor instead.`, + internalCommentOnUnexported: `@internal should not appear on an unexported declaration.`, + internalCommentOnPrivate: `@internal should not appear on a private declaration.`, + }, + schema: [], + type: "problem", + fixable: "whitespace", + }, + defaultOptions: [], + + create(context) { + const sourceCode = context.sourceCode; + const atInternal = "@internal"; + const jsdocStart = "/**"; + + /** @type {Map} */ + const isExportedCache = new Map(); + + /** @type {(node: TSESTree.Node) => boolean} */ + function isExported(node) { + const exported = isExportedCache.get(node); + if (exported !== undefined) { + return exported; + } + + /** @type {TSESTree.Node | undefined} */ + let current = node; + while (current) { + // https://github.com/typescript-eslint/typescript-eslint/blob/e44a1a280f08f9fd0d29f74e5c3e73b7b64a9606/packages/eslint-plugin/src/util/collectUnusedVariables.ts#L440 + if (current.type.startsWith("Export")) { + isExportedCache.set(node, true); + return true; + } + isExportedCache.set(current, false); + current = current.parent; + } + + return false; + } + + /** @type {(text: string) => boolean} */ + function isJSDocText(text) { + return text.startsWith(jsdocStart); + } + + /** @type {(c: TSESTree.Comment, indexInComment: number) => TSESTree.SourceLocation} */ + const getAtInternalLoc = (c, indexInComment) => { + return { + start: context.sourceCode.getLocFromIndex(c.range[0] + indexInComment), + end: context.sourceCode.getLocFromIndex(c.range[0] + indexInComment + atInternal.length), + }; + }; + + /** @type {(c: TSESTree.Comment) => TSESTree.SourceLocation} */ + const getJSDocStartLoc = c => { + return { + start: c.loc.start, + end: { + line: c.loc.start.line, + column: c.loc.start.column + jsdocStart.length, + }, + }; + }; + + /** @type {(node: TSESTree.Node) => void} */ + const checkDeclaration = node => { + const blockComments = sourceCode.getCommentsBefore(node).filter(c => c.type === "Block"); + if (blockComments.length === 0) { + return; + } + + const last = blockComments.length - 1; + let seenJSDoc = false; + for (let i = 0; i < blockComments.length; i++) { + const c = blockComments[i]; + const rawComment = sourceCode.getText(c); + + const isJSDoc = isJSDocText(rawComment); + if (isJSDoc && seenJSDoc) { + context.report({ messageId: "multipleJSDocError", node: c, loc: getJSDocStartLoc(c) }); + } + seenJSDoc = seenJSDoc || isJSDoc; + + const indexInComment = rawComment.indexOf(atInternal); + if (indexInComment === -1) { + continue; + } + + if (!isJSDoc) { + context.report({ messageId: "internalCommentInNonJSDocError", node: c, loc: getAtInternalLoc(c, indexInComment) }); + } + else if (node.type === "TSParameterProperty") { + context.report({ messageId: "internalCommentOnParameterProperty", node: c, loc: getAtInternalLoc(c, indexInComment) }); + } + else if (!isExported(node)) { + context.report({ messageId: "internalCommentOnUnexported", node: c, loc: getAtInternalLoc(c, indexInComment) }); + } + // eslint-disable-next-line local/no-in-operator + else if ("accessibility" in node && node.accessibility === "private") { + context.report({ messageId: "internalCommentOnPrivate", node: c, loc: getAtInternalLoc(c, indexInComment) }); + } + else if (i !== last) { + context.report({ messageId: "internalCommentNotLastError", node: c, loc: getAtInternalLoc(c, indexInComment) }); + } + } + }; + + return { + ClassDeclaration: checkDeclaration, + FunctionDeclaration: checkDeclaration, + TSEnumDeclaration: checkDeclaration, + TSModuleDeclaration: checkDeclaration, + VariableDeclaration: checkDeclaration, + TSInterfaceDeclaration: checkDeclaration, + TSTypeAliasDeclaration: checkDeclaration, + TSCallSignatureDeclaration: checkDeclaration, + ExportAllDeclaration: checkDeclaration, + ExportNamedDeclaration: checkDeclaration, + TSImportEqualsDeclaration: checkDeclaration, + TSNamespaceExportDeclaration: checkDeclaration, + TSConstructSignatureDeclaration: checkDeclaration, + ExportDefaultDeclaration: checkDeclaration, + TSPropertySignature: checkDeclaration, + TSIndexSignature: checkDeclaration, + TSMethodSignature: checkDeclaration, + TSParameterProperty: checkDeclaration, + PropertyDefinition: checkDeclaration, + MethodDefinition: checkDeclaration, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs b/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs new file mode 100644 index 0000000000000..54c87497a6a9a --- /dev/null +++ b/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs @@ -0,0 +1,126 @@ +const { ESLintUtils } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); +const { getConstrainedTypeAtLocation, isTypeArrayTypeOrUnionOfArrayTypes } = require("@typescript-eslint/type-utils"); + +/** + * @import { TSESTree } from "@typescript-eslint/utils" + */ +void 0; + +module.exports = createRule({ + name: "no-array-mutating-method-expressions", + meta: { + docs: { + description: ``, + }, + messages: { + noSideEffectUse: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy the array with slice.`, + noSideEffectUseToMethod: `This call to {{method}} appears to be unintentional as it appears in an expression position. Sort the array in a separate statement or explicitly copy and slice the array with slice/{{toMethod}}.`, + }, + schema: [], + type: "problem", + }, + defaultOptions: [], + + create(context) { + const services = ESLintUtils.getParserServices(context, /*allowWithoutFullTypeInformation*/ true); + if (!services.program) { + return {}; + } + + const checker = services.program.getTypeChecker(); + + /** + * This is a heuristic to ignore cases where the mutating method appears to be + * operating on a "fresh" array. + * + * @type {(callee: TSESTree.MemberExpression) => boolean} + */ + const isFreshArray = callee => { + const object = callee.object; + + if (object.type === "ArrayExpression") { + return true; + } + + if (object.type !== "CallExpression") { + return false; + } + + if (object.callee.type === "Identifier") { + // TypeScript codebase specific helpers. + // TODO(jakebailey): handle ts. + switch (object.callee.name) { + case "arrayFrom": + case "getOwnKeys": + return true; + } + return false; + } + + if (object.callee.type === "MemberExpression" && object.callee.property.type === "Identifier") { + switch (object.callee.property.name) { + case "concat": + case "filter": + case "map": + case "slice": + return true; + } + + if (object.callee.object.type === "Identifier") { + if (object.callee.object.name === "Array") { + switch (object.callee.property.name) { + case "from": + case "of": + return true; + } + return false; + } + + if (object.callee.object.name === "Object") { + switch (object.callee.property.name) { + case "values": + case "keys": + case "entries": + return true; + } + return false; + } + } + } + + return false; + }; + + /** @type {(callee: TSESTree.MemberExpression & { parent: TSESTree.CallExpression; }, method: string, toMethod: string | undefined) => void} */ + const check = (callee, method, toMethod) => { + if (callee.parent.parent.type === "ExpressionStatement") return; + if (isFreshArray(callee)) return; + + const calleeObjType = getConstrainedTypeAtLocation(services, callee.object); + if (!isTypeArrayTypeOrUnionOfArrayTypes(calleeObjType, checker)) return; + + if (toMethod) { + context.report({ node: callee.property, messageId: "noSideEffectUseToMethod", data: { method, toMethod } }); + } + else { + context.report({ node: callee.property, messageId: "noSideEffectUse", data: { method } }); + } + }; + + // Methods with new copying variants. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#copying_methods_and_mutating_methods + const mutatingMethods = { + reverse: undefined, + sort: "toSorted", // This exists as `ts.toSorted`, so recommend that. + splice: undefined, + }; + + return Object.fromEntries( + Object.entries(mutatingMethods).map(([method, toMethod]) => [ + `CallExpression > MemberExpression[property.name='${method}'][computed=false]`, + node => check(node, method, toMethod), + ]), + ); + }, +}); diff --git a/packages/typescript/eslint/rules/no-in-operator.cjs b/packages/typescript/eslint/rules/no-in-operator.cjs new file mode 100644 index 0000000000000..94f181d259e1e --- /dev/null +++ b/packages/typescript/eslint/rules/no-in-operator.cjs @@ -0,0 +1,33 @@ +const { createRule } = require("./utils.cjs"); + +/** @import { TSESTree } from "@typescript-eslint/utils" */ +void 0; + +module.exports = createRule({ + name: "no-in-operator", + meta: { + docs: { + description: ``, + }, + messages: { + noInOperatorError: `Don't use the 'in' keyword - use 'hasProperty' to check for key presence instead`, + }, + schema: [], + type: "suggestion", + }, + defaultOptions: [], + + create(context) { + const IN_OPERATOR = "in"; + /** @type {(node: TSESTree.BinaryExpression) => void} */ + const checkInOperator = node => { + if (node.operator === IN_OPERATOR) { + context.report({ messageId: "noInOperatorError", node }); + } + }; + + return { + BinaryExpression: checkInOperator, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/no-keywords.cjs b/packages/typescript/eslint/rules/no-keywords.cjs new file mode 100644 index 0000000000000..668d059ac993e --- /dev/null +++ b/packages/typescript/eslint/rules/no-keywords.cjs @@ -0,0 +1,117 @@ +const { AST_NODE_TYPES } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); + +/** @import { TSESTree } from "@typescript-eslint/utils" */ +void 0; + +module.exports = createRule({ + name: "no-keywords", + meta: { + docs: { + description: `disallows the use of certain TypeScript keywords as variable or parameter names`, + }, + messages: { + noKeywordsError: `{{ name }} clashes with keyword/type`, + }, + schema: [{ + properties: { + properties: { type: "boolean" }, + keywords: { type: "boolean" }, + }, + type: "object", + }], + type: "suggestion", + }, + defaultOptions: [], + + create(context) { + const keywords = [ + "Undefined", + "undefined", + "Boolean", + "boolean", + "String", + "string", + "Number", + "number", + "any", + ]; + + /** @type {(name: string) => boolean} */ + const isKeyword = name => keywords.includes(name); + + /** @type {(node: TSESTree.Identifier) => void} */ + const report = node => { + context.report({ messageId: "noKeywordsError", data: { name: node.name }, node }); + }; + + /** @type {(node: TSESTree.ObjectPattern) => void} */ + const checkProperties = node => { + node.properties.forEach(property => { + if ( + property && + property.type === AST_NODE_TYPES.Property && + property.key.type === AST_NODE_TYPES.Identifier && + isKeyword(property.key.name) + ) { + report(property.key); + } + }); + }; + + /** @type {(node: TSESTree.ArrayPattern) => void} */ + const checkElements = node => { + node.elements.forEach(element => { + if ( + element && + element.type === AST_NODE_TYPES.Identifier && + isKeyword(element.name) + ) { + report(element); + } + }); + }; + + /** @type {(node: TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration | TSESTree.FunctionExpression | TSESTree.TSMethodSignature | TSESTree.TSFunctionType) => void} */ + const checkParams = node => { + if (!node || !node.params || !node.params.length) { + return; + } + + node.params.forEach(param => { + if ( + param && + param.type === AST_NODE_TYPES.Identifier && + isKeyword(param.name) + ) { + report(param); + } + }); + }; + + return { + VariableDeclarator(node) { + if (node.id.type === AST_NODE_TYPES.ObjectPattern) { + checkProperties(node.id); + } + + if (node.id.type === AST_NODE_TYPES.ArrayPattern) { + checkElements(node.id); + } + + if ( + node.id.type === AST_NODE_TYPES.Identifier && + isKeyword(node.id.name) + ) { + report(node.id); + } + }, + + ArrowFunctionExpression: checkParams, + FunctionDeclaration: checkParams, + FunctionExpression: checkParams, + TSMethodSignature: checkParams, + TSFunctionType: checkParams, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/only-arrow-functions.cjs b/packages/typescript/eslint/rules/only-arrow-functions.cjs new file mode 100644 index 0000000000000..37c5ec667b9d9 --- /dev/null +++ b/packages/typescript/eslint/rules/only-arrow-functions.cjs @@ -0,0 +1,91 @@ +const { AST_NODE_TYPES } = require("@typescript-eslint/utils"); +const { createRule } = require("./utils.cjs"); + +/** + * @import { TSESTree } from "@typescript-eslint/utils" + * @typedef {TSESTree.FunctionDeclaration | TSESTree.FunctionExpression} FunctionDeclarationOrExpression + */ +void 0; + +module.exports = createRule({ + name: "only-arrow-functions", + meta: { + docs: { + description: `Disallows traditional (non-arrow) function expressions.`, + }, + messages: { + onlyArrowFunctionsError: "non-arrow functions are forbidden", + }, + schema: [{ + additionalProperties: false, + properties: { + allowNamedFunctions: { type: "boolean" }, + allowDeclarations: { type: "boolean" }, + }, + type: "object", + }], + type: "suggestion", + }, + /** @type {[{ allowNamedFunctions?: boolean; allowDeclarations?: boolean }]} */ + defaultOptions: [{ + allowNamedFunctions: false, + allowDeclarations: false, + }], + + create(context, [{ allowNamedFunctions, allowDeclarations }]) { + /** @type {(node: FunctionDeclarationOrExpression) => boolean} */ + const isThisParameter = node => !!node.params.length && !!node.params.find(param => param.type === AST_NODE_TYPES.Identifier && param.name === "this"); + + /** @type {(node: TSESTree.Node) => boolean} */ + const isMethodType = node => { + const types = [ + AST_NODE_TYPES.MethodDefinition, + AST_NODE_TYPES.Property, + ]; + + const parent = node.parent; + if (!parent) { + return false; + } + + return node.type === AST_NODE_TYPES.FunctionExpression && types.includes(parent.type); + }; + + /** @type {boolean[]} */ + const stack = []; + const enterFunction = () => { + stack.push(false); + }; + + const markThisUsed = () => { + if (stack.length) { + stack[stack.length - 1] = true; + } + }; + + /** @type {(node: FunctionDeclarationOrExpression) => void} */ + const exitFunction = node => { + const methodUsesThis = stack.pop(); + + if (node.type === AST_NODE_TYPES.FunctionDeclaration && allowDeclarations) { + return; + } + + if ((allowNamedFunctions && node.id !== null) || isMethodType(node)) { // eslint-disable-line no-restricted-syntax + return; + } + + if (!(node.generator || methodUsesThis || isThisParameter(node))) { + context.report({ messageId: "onlyArrowFunctionsError", node }); + } + }; + + return { + "FunctionDeclaration": enterFunction, + "FunctionDeclaration:exit": exitFunction, + "FunctionExpression": enterFunction, + "FunctionExpression:exit": exitFunction, + "ThisExpression": markThisUsed, + }; + }, +}); diff --git a/packages/typescript/eslint/rules/utils.cjs b/packages/typescript/eslint/rules/utils.cjs new file mode 100644 index 0000000000000..6c6bae010a1db --- /dev/null +++ b/packages/typescript/eslint/rules/utils.cjs @@ -0,0 +1,2 @@ +const { ESLintUtils } = require("@typescript-eslint/utils"); +module.exports.createRule = ESLintUtils.RuleCreator(() => ""); diff --git a/packages/typescript/package.json b/packages/typescript/package.json index 2a375beedce6f..8e659ce800c13 100644 --- a/packages/typescript/package.json +++ b/packages/typescript/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@typescript/typescript", - "version": "0.0.0", + "version": "7.1.0", "license": "Apache-2.0", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", diff --git a/packages/typescript/scripts/tsconfig.json b/packages/typescript/scripts/tsconfig.json new file mode 100644 index 0000000000000..4a90260fcbb06 --- /dev/null +++ b/packages/typescript/scripts/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../tsconfig.dev.json", + "include": ["*.ts"] +} diff --git a/packages/vscode-typescript/package.json b/packages/vscode-typescript/package.json index fc85667031a2a..54e67462d720a 100644 --- a/packages/vscode-typescript/package.json +++ b/packages/vscode-typescript/package.json @@ -415,7 +415,7 @@ "vscode-tas-client": "^0.3.3" }, "devDependencies": { - "@typescript/typescript": "0.0.0", + "@typescript/typescript": "7.1.0", "@types/vscode": "~1.125.0", "@typescript/bundled-typescript": "npm:typescript@7.0.2", "@vscode/vsce": "4.1.0", From 09ea4d1b54fe56c1921b91ece5189899b772d226 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 16:12:49 -0800 Subject: [PATCH 2/3] Fix lint errors --- CONTRIBUTING.md | 3 - Herebyfile.mjs | 1 - eslint.config.mjs | 19 +- packages/typescript/eslint/lint.test.mjs | 49 -- packages/typescript/scripts/generateSync.ts | 30 +- packages/typescript/src/api/async/api.ts | 57 +- packages/typescript/src/api/async/client.ts | 8 +- packages/typescript/src/api/async/jsonrpc.ts | 9 +- .../src/api/async/transportClient.ts | 11 +- packages/typescript/src/api/fsCallbacks.ts | 12 +- packages/typescript/src/api/node/encoder.ts | 10 +- packages/typescript/src/api/node/msgpack.ts | 12 +- .../src/api/node/node.infrastructure.ts | 27 +- packages/typescript/src/api/node/node.ts | 63 ++- packages/typescript/src/api/node/wtf8.ts | 7 +- packages/typescript/src/api/options.ts | 4 +- packages/typescript/src/api/path.ts | 6 +- packages/typescript/src/api/printer.ts | 3 +- packages/typescript/src/api/proto.ts | 6 +- .../typescript/src/api/sourceFileCache.ts | 3 +- packages/typescript/src/api/sync/api.ts | 93 ++-- packages/typescript/src/api/sync/client.ts | 2 +- .../src/api/sync/generatorSupport.ts | 8 +- .../src/api/sync/transportClient.ts | 2 +- packages/typescript/src/api/syncChannel.ts | 22 +- packages/typescript/src/api/timing.ts | 2 +- packages/typescript/src/api/timingDump.ts | 1 + packages/typescript/src/ast/astnav.ts | 2 +- packages/typescript/src/ast/is.ts | 18 +- packages/typescript/src/ast/scanner.ts | 18 +- packages/typescript/src/ast/spanMap.ts | 37 +- packages/typescript/src/ast/utils.ts | 44 +- packages/typescript/src/ast/visitor.ts | 3 - .../typescript/src/vscode/extensionApi.ts | 5 +- .../typescript/src/vscode/moduleLoader.ts | 8 +- packages/typescript/src/wasm/transport.ts | 7 +- packages/typescript/src/wasm/wasi.ts | 20 +- .../typescript/test/api-comparison.bench.ts | 22 +- .../typescript/test/astPredicates.test.ts | 216 +++++--- packages/typescript/test/async/api.test.ts | 489 +++++++++--------- packages/typescript/test/async/astnav.test.ts | 2 +- .../typescript/test/async/transport.test.ts | 72 ++- .../typescript/test/browser/smoke.test.ts | 4 +- .../test/diagnosticFormatter.test.ts | 4 +- packages/typescript/test/encoder.test.ts | 92 ++-- packages/typescript/test/nodelist.bench.ts | 5 +- packages/typescript/test/path.test.ts | 60 +-- packages/typescript/test/proto.test.ts | 42 +- .../test/sync/api-generators.test.ts | 87 ++-- packages/typescript/test/sync/api.test.ts | 485 ++++++++--------- packages/typescript/test/sync/ast.bench.ts | 3 +- packages/typescript/test/sync/ast.test.ts | 116 ++--- packages/typescript/test/sync/astnav.test.ts | 2 +- .../typescript/test/sync/shutdown.test.ts | 1 + packages/typescript/test/sync/timing.test.ts | 2 +- .../typescript/test/sync/transport.test.ts | 2 +- packages/typescript/test/sync/wasm.test.ts | 20 +- packages/typescript/test/testUtils.ts | 7 +- packages/typescript/test/wasm.ts | 6 +- 59 files changed, 1264 insertions(+), 1107 deletions(-) delete mode 100644 packages/typescript/eslint/lint.test.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d321845fe8970..1de7e023945ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -143,9 +143,6 @@ the pinned LSP model when its local cache is missing or stale. Use `generate:go` for the narrower scope of `go generate ./...` in the `tsc` module. Up-to-date generators emit no status messages. -TypeScript linting uses the experimental native typescript-eslint project service, -the local API build, and `built/local/tsc`. The lint tasks build these prerequisites. - `npx hereby build` runs `generate` before compiling; a separate generation step is not needed. The API and package build tasks share this prerequisite, and `build:watch` runs the full incremental generation suite before every rebuild. diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 8b0cd09007853..7a089bc343c81 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -1453,7 +1453,6 @@ async function runLint() { } async function runLintTypeScript() { - await run("node", ["--test", "packages/typescript/eslint/lint.test.mjs"]); const args = ["packages/typescript/{src,test,scripts}/**/*.ts"]; if (options.fix) { args.push("--fix"); diff --git a/eslint.config.mjs b/eslint.config.mjs index 6cc6b8b73f120..78dec82749953 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -46,8 +46,8 @@ export default tseslint.config( }, }, rules: { - "dot-notation": "error", - "eqeqeq": "error", + "dot-notation": "off", + "eqeqeq": "off", // Enforced below with an exception for nullish comparisons. "no-caller": "error", "no-constant-condition": ["error", { checkLoops: false }], "no-eval": "error", @@ -67,6 +67,10 @@ export default tseslint.config( "error", { selector: "Literal[raw=null]", message: "Avoid using null; use undefined instead." }, { selector: "TSNullKeyword", message: "Avoid using null; use undefined instead." }, + { + selector: "BinaryExpression[operator=/^(==|!=)$/]:not([left.type='Identifier'][left.name='undefined']):not([right.type='Identifier'][right.name='undefined'])", + message: "Expected strict equality unless comparing with undefined.", + }, ], "no-extra-boolean-cast": "off", "no-case-declarations": "off", @@ -75,17 +79,22 @@ export default tseslint.config( "no-inner-declarations": "off", "@typescript-eslint/naming-convention": [ "error", - { selector: "typeLike", format: ["PascalCase"], filter: { regex: "^(__String|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "typeLike", format: ["PascalCase"], leadingUnderscore: "allow", filter: { regex: "^(__String|[A-Za-z]+_[A-Za-z]+)$", match: false } }, { selector: "interface", format: ["PascalCase"], custom: { regex: "^I[A-Z]", match: false }, filter: { regex: "^I(Arguments|TextWriter|O([A-Z][a-z]+[A-Za-z]*)?)$", match: false } }, { selector: "variable", format: ["camelCase", "PascalCase", "UPPER_CASE"], leadingUnderscore: "allow", filter: { regex: "^(_{1,2}filename|_{1,2}dirname|_+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, { selector: "function", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^[A-Za-z]+_[A-Za-z]+$", match: false } }, { selector: "parameter", format: ["camelCase"], leadingUnderscore: "allow", filter: { regex: "^(_+|[A-Za-z]+_[A-Z][a-z]+)$", match: false } }, - { selector: "method", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, - { selector: "memberLike", format: ["camelCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+_[A-Za-z]+)$", match: false } }, + { selector: "method", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+(?:_[A-Za-z]+)+)$", match: false } }, + { selector: "memberLike", format: ["camelCase"], leadingUnderscore: "allow", filter: { regex: "^([0-9]+|[A-Za-z]+(?:_[A-Za-z]+)+)$", match: false } }, { selector: "enumMember", format: ["camelCase", "PascalCase"], leadingUnderscore: "allow", filter: { regex: "^[A-Za-z]+_[A-Za-z]+$", match: false } }, { selector: "property", format: null }, ], "@typescript-eslint/unified-signatures": "error", + "@typescript-eslint/dot-notation": ["error", { + allowIndexSignaturePropertyAccess: true, + allowPrivateClassPropertyAccess: true, + allowProtectedClassPropertyAccess: true, + }], "no-unused-expressions": "off", "@typescript-eslint/no-unused-expressions": ["error", { allowTernary: true }], "@typescript-eslint/ban-ts-comment": "off", diff --git a/packages/typescript/eslint/lint.test.mjs b/packages/typescript/eslint/lint.test.mjs deleted file mode 100644 index 03d594034b844..0000000000000 --- a/packages/typescript/eslint/lint.test.mjs +++ /dev/null @@ -1,49 +0,0 @@ -import { API } from "@typescript/native/sync"; -import { ESLint } from "eslint"; -import assert from "node:assert/strict"; -import path from "node:path"; -import { test } from "node:test"; -import getExePath from "../lib/getExePath.js"; - -test("lint uses the local native API for typed custom rules", async () => { - const root = path.resolve(import.meta.dirname, "../../.."); - const executable = getExePath({ - fs: process.getBuiltinModule("node:fs"), - module: process.getBuiltinModule("node:module"), - path: process.getBuiltinModule("node:path"), - url: process.getBuiltinModule("node:url"), - }); - assert.equal(executable, path.join(root, "built/local", process.platform === "win32" ? "tsc.exe" : "tsc")); - - const descriptor = Object.getOwnPropertyDescriptor(API.prototype, "createSnapshot"); - assert.ok(descriptor?.get); - let snapshots = 0; - Object.defineProperty(API.prototype, "createSnapshot", { - ...descriptor, - get() { - snapshots++; - return descriptor.get.call(this); - }, - }); - try { - const eslint = new ESLint({ cwd: root }); - const filePath = "packages/typescript/src/internal/lint-probe.ts"; - const [result] = await eslint.lintText( - "function check(flag: boolean) { return flag; }\ncheck(true);\nconst xs: number[] = [1];\nconst ys = xs.sort();\n", - { filePath }, - ); - assert.ok(snapshots > 0, "lint must create a native snapshot"); - const argument = result.messages.find(message => message.ruleId === "local/argument-trivia"); - assert.equal(argument?.fix?.text, "/*flag*/ "); - assert.ok(result.messages.some(message => message.ruleId === "local/no-array-mutating-method-expressions")); - - const [imports] = await eslint.lintText( - 'import "./missing";\nimport "./present.ts";\nimport "./present.js";\nimport "./present.json";\n', - { filePath }, - ); - assert.equal(imports.messages.filter(message => message.ruleId === "local/js-extensions").length, 1); - } - finally { - Object.defineProperty(API.prototype, "createSnapshot", descriptor); - } -}); diff --git a/packages/typescript/scripts/generateSync.ts b/packages/typescript/scripts/generateSync.ts index 3988cf5f8f17e..ab3630c48636f 100755 --- a/packages/typescript/scripts/generateSync.ts +++ b/packages/typescript/scripts/generateSync.ts @@ -48,7 +48,7 @@ function generatedHeader(asyncSourceRelPath: string): string { ].join("\n"); } -const ROOT = join(import.meta.dirname!, ".."); +const ROOT = join(import.meta.dirname, ".."); const SRC = join(ROOT, "src", "api"); const TEST = join(ROOT, "test"); @@ -209,7 +209,7 @@ function applyEdits(source: string, edits: Edit[]): string { type TransformMode = "sync" | "generator"; function transformAsyncSource(source: string, fileName: string, attachGenerators: boolean): string { - const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true); + const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, /*setParentNodes*/ true); const edits: Edit[] = []; const asyncMethodNames = new Set(); const synchronousMethodNames = new Set(); @@ -301,7 +301,7 @@ function transformAsyncSource(source: string, fileName: string, attachGenerators const generatorSignatures = declarations.map(declaration => `${indent} gen${createAsyncCallSignature(declaration, "generator")}`).join("\n"); const body = declarations.length > 1 ? createAsyncOverloadedGetterBody(name, group, indent) - : `{\n${indent} const owner = this;\n${indent} return cacheGeneratorMethod(\n${indent} owner,\n${indent} "${name}",\n${indent} ${createAsyncFunction(method, "sync", false)},\n${indent} ${createAsyncFunction(method, "generator", true)},\n${indent} );\n${indent}}`; + : `{\n${indent} const owner = this;\n${indent} return cacheGeneratorMethod(\n${indent} owner,\n${indent} "${name}",\n${indent} ${createAsyncFunction(method, "sync", /*generator*/ false)},\n${indent} ${createAsyncFunction(method, "generator", /*generator*/ true)},\n${indent} );\n${indent}}`; return `${modifiers ? `${modifiers} ` : ""}get ${name}(): {\n${syncSignatures}\n${generatorSignatures}\n${indent}} ${body}`; } @@ -309,8 +309,8 @@ function transformAsyncSource(source: string, fileName: string, attachGenerators const declarations = getPublicDeclarations(group); const syncOverloads = declarations.map(declaration => `function ${name}${createAsyncCallSignature(declaration, "sync")}`).join("\n"); const generatorOverloads = declarations.map(declaration => `function gen${createAsyncCallSignature(declaration, "generator")}`).join("\n"); - const syncImplementation = createAsyncNamedFunction(name, group.implementation, "sync", false); - const generatorImplementation = createAsyncNamedFunction("gen", group.implementation, "generator", true); + const syncImplementation = createAsyncNamedFunction(name, group.implementation, "sync", /*generator*/ false); + const generatorImplementation = createAsyncNamedFunction("gen", group.implementation, "generator", /*generator*/ true); return `{\n${indent} const owner = this;\n${indent}${indentLines(syncOverloads, `${indent} `)}\n${indent}${indentLines(syncImplementation, `${indent} `)}\n${indent}${indentLines(generatorOverloads, `${indent} `)}\n${indent}${indentLines(generatorImplementation, `${indent} `)}\n${indent} return cacheGeneratorMethod(owner, "${name}", ${name}, gen);\n${indent}}`; } @@ -319,14 +319,14 @@ function transformAsyncSource(source: string, fileName: string, attachGenerators } function createAsyncFunction(node: ts.MethodDeclaration, mode: TransformMode, generator: boolean): string { - const parameters = node.parameters.map(parameter => transformNodeText(parameter, mode, true)).join(", "); - const body = transformNodeText(node.body!, mode, true); + const parameters = node.parameters.map(parameter => transformNodeText(parameter, mode, /*replaceThis*/ true)).join(", "); + const body = transformNodeText(node.body!, mode, /*replaceThis*/ true); return `function${generator ? "*" : ""} ${getTypeParametersText(node, source, sourceFile)}(${parameters}): ${getAsyncReturnType(node, mode)} ${body}`; } function createAsyncNamedFunction(name: string, node: ts.MethodDeclaration, mode: TransformMode, generator: boolean): string { - const parameters = node.parameters.map(parameter => transformNodeText(parameter, mode, true)).join(", "); - const body = transformNodeText(node.body!, mode, true); + const parameters = node.parameters.map(parameter => transformNodeText(parameter, mode, /*replaceThis*/ true)).join(", "); + const body = transformNodeText(node.body!, mode, /*replaceThis*/ true); return `function${generator ? "*" : ""} ${name}${getTypeParametersText(node, source, sourceFile)}(${parameters}): ${getAsyncReturnType(node, mode)} ${body}`; } @@ -335,7 +335,7 @@ function transformAsyncSource(source: string, fileName: string, attachGenerators const rest = parameter.dotDotDotToken ? "..." : ""; const name = source.slice(parameter.name.getStart(sourceFile), parameter.name.end); const optional = parameter.questionToken || parameter.initializer ? "?" : ""; - const type = parameter.type ? transformNodeText(parameter.type, mode, false) : "unknown"; + const type = parameter.type ? transformNodeText(parameter.type, mode, /*replaceThis*/ false) : "unknown"; return `${rest}${name}${optional}: ${type}`; }).join(", "); } @@ -349,7 +349,7 @@ function transformAsyncSource(source: string, fileName: string, attachGenerators } return `Generator`; } - return transformNodeText(node.type, mode, false); + return transformNodeText(node.type, mode, /*replaceThis*/ false); } function transformNodeText(node: ts.Node, mode: TransformMode, replaceThis: boolean): string { @@ -704,13 +704,13 @@ export function generateSync(force = false): void { 'import type { APIRequest as ProtocolRequest, APIResponse as ProtocolResponse } from "../proto.ts";', 'import { all, apiRequest, cacheGeneratorMethod, type APIRequestGenerator } from "./generatorSupport.ts";', "", - transformAsyncSource(source, fileName, true), + transformAsyncSource(source, fileName, /*attachGenerators*/ true), ].join("\n") : (source, fileName) => [ 'import type { APIRequest as ProtocolRequest, APIResponse as ProtocolResponse } from "../proto.ts";', "", - transformAsyncSource(source, fileName, true), + transformAsyncSource(source, fileName, /*attachGenerators*/ true), ].join("\n"), force, "sync", @@ -723,7 +723,7 @@ export function generateSync(force = false): void { generatedFiles.push(generateSyncFile( join(TEST, "async", relPath), join(TEST, "sync", relPath), - (source, fileName) => transformAsyncSource(source, fileName, false), + (source, fileName) => transformAsyncSource(source, fileName, /*attachGenerators*/ false), force, )); } @@ -731,7 +731,7 @@ export function generateSync(force = false): void { generatedFiles.push(generateSyncFile( join(TEST, "async", "api.bench.ts"), join(TEST, "generators", "api.bench.ts"), - (source, fileName) => transformAsyncSource(source, fileName, false), + (source, fileName) => transformAsyncSource(source, fileName, /*attachGenerators*/ false), force, "generators", )); diff --git a/packages/typescript/src/api/async/api.ts b/packages/typescript/src/api/async/api.ts index 8dfe0d008cb1a..d2fd34ac10202 100644 --- a/packages/typescript/src/api/async/api.ts +++ b/packages/typescript/src/api/async/api.ts @@ -59,8 +59,6 @@ import { getNodeId, getNodeRequestHandle, parseNodeHandleFromCompiler, - readParseOptionsKey, - readSourceFileHash, readSourceFileLease, RemoteNode, RemoteSourceFile, @@ -98,7 +96,6 @@ import type { CreateSnapshotResponse, CreateSourceFileOptions, Diagnostic, - DiagnosticResponse, DocumentIdentifier, DocumentPosition, EmitOutputResponse as ProtocolEmitOutputResponse, @@ -152,7 +149,6 @@ import { import type { RequestTiming, TimingAccumulators, - TimingCollector, TimingInfo, } from "../timing.ts"; import { @@ -470,7 +466,8 @@ export class API implements FormatDiagnosticsHo private async initializeWorker(): Promise { try { - const response = await this.client.apiRequest("initialize", null); + // eslint-disable-next-line no-restricted-syntax -- The initialize request requires null parameters. + const response = await this.client.apiRequest("initialize", /*params*/ null); this.currentDirectory = response.currentDirectory; this.caseSensitivity = response.caseSensitivity; this.toPath = (fileName: string, basePath = response.currentDirectory) => pathKey(toRootedPath(fileName, toRootedDirectoryPath(basePath, response.currentDirectory)), response.caseSensitivity); @@ -666,7 +663,7 @@ export class API implements FormatDiagnosticsHo this.sourceFileCache.releaseSnapshot(snapshot.id); }, this.createSnapshotUpdater(() => snapshot), - undefined, + /*baseSnapshot*/ undefined, ); this.activeSnapshots.set(snapshot.id, snapshot); @@ -766,8 +763,8 @@ export class API implements FormatDiagnosticsHo ): Promise { await this.ensureInitialized(); - const changes = args[0] as LanguageServerSnapshotChanges | undefined; - const baseSnapshot = args[1] as Snapshot | undefined; + const changes = args[0]; + const baseSnapshot = args[1]; if (baseSnapshot && (this.activeSnapshots.get(baseSnapshot.id) !== baseSnapshot || baseSnapshot.isDisposed())) { throw new Error("Cannot use an inactive snapshot as a response base"); } @@ -905,7 +902,7 @@ export class API implements FormatDiagnosticsHo const snapshot = await this.createSnapshot({ createPrograms: [{ rootFiles, compilerOptions, options: createProgramOptions }], }); - const program = snapshot.operation.createdPrograms![0]; + const program = snapshot.operation.createdPrograms[0]; if (!program) { await snapshot.dispose(); throw new Error("createProgram did not return a project"); @@ -1016,7 +1013,8 @@ export class DebugHandlers { async stopCPUProfile(): Promise { await this.ensureInitialized(); - const result = await this.client.apiRequest("stopCPUProfile", null); + // eslint-disable-next-line no-restricted-syntax -- The stopCPUProfile request requires null parameters. + const result = await this.client.apiRequest("stopCPUProfile", /*params*/ null); return result.file; } @@ -1488,7 +1486,7 @@ class ProjectObjectRegistry { project: this.project.handle, objectId: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; else return typesData.map(data => this.getOrCreateType(data)); } @@ -1526,7 +1524,7 @@ class ProjectObjectRegistry { project: this.project.handle, type: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; return typesData.map(data => this.getOrCreateType(data)); } @@ -2042,7 +2040,7 @@ export class Program implements FormatDiagnost return undefined; } - return new RemoteSourceFile(binaryData, this.decoder, undefined, this.project.api) as unknown as SourceFile; + return new RemoteSourceFile(binaryData, this.decoder, /*timing*/ undefined, this.project.api) as unknown as SourceFile; } /** @@ -2347,6 +2345,10 @@ function encodeNumberLiteralValue(value: number): number | string { return value; } +function isNodeLocation(location: Node | DocumentPosition): location is Node { + return !!(location as Node).kind; +} + export class Checker { /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ async getRootSymbols(symbol: Symbol): Promise { @@ -2661,15 +2663,15 @@ export class Checker { excludeGlobals?: boolean, ): Promise { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = location && "kind" in location; + const isNode = location && isNodeLocation(location); const data = await this.client.apiRequest("resolveName", { snapshot: this.snapshotId, project: this.project.handle, name, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: !isNode && location ? (location as DocumentPosition).document : undefined, - position: !isNode && location ? (location as DocumentPosition).position : undefined, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: !isNode && location ? location.document : undefined, + position: !isNode && location ? location.position : undefined, excludeGlobals, }); return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; @@ -2680,14 +2682,14 @@ export class Checker { */ async getSymbolsInScope(location: Node | DocumentPosition, meaning: SymbolFlags): Promise { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = "kind" in location; + const isNode = isNodeLocation(location); const data = await this.client.apiRequest("getSymbolsInScope", { snapshot: this.snapshotId, project: this.project.handle, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: isNode ? undefined : (location as DocumentPosition).document, - position: isNode ? undefined : (location as DocumentPosition).position, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: isNode ? undefined : location.document, + position: isNode ? undefined : location.position, }); return data ? data.map(d => this.objectRegistry.getOrCreateSymbol(d)) : []; } @@ -2965,7 +2967,7 @@ export class Checker { flags, }); if (!binaryData) return undefined; - return decodeNode(binaryData) as Node; + return decodeNode(binaryData); } async symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Promise { @@ -3669,7 +3671,7 @@ export class Symbol { // A file-owned symbol has no canonical project; its declarations resolve through its file. return this.storage.kind === SymbolOwnerKind.Snapshot ? this.storage.registry.createNodeHandle(handle) - : new NodeHandle(handle, undefined, this.storage.owner); + : new NodeHandle(handle, /*canonicalProject*/ undefined, this.storage.owner); } async getParent(): Promise { @@ -3812,12 +3814,13 @@ class TypeObject implements Type { this.flags = data.flags; this.objectFlags = data.objectFlags ?? 0; if (data.symbol !== undefined) this.symbol = data.symbol; - if (data.value != null) { + const typeValue = data.value; + if (typeValue != undefined) { // BigInt literal values are serialized as decimal strings (e.g. "-123") because // JSON cannot represent bigint. Decode them back into a real bigint here. - const value = data.value as string | number | boolean; + const value = typeValue as string | number | boolean; if (data.flags & TypeFlags.BigIntLiteral) { - this.value = BigInt(value as string); + this.value = BigInt(value); } // JSON cannot represent infinities, so the API serializes them as strings. else if (data.flags & TypeFlags.NumberLiteral && typeof value === "string") { @@ -4012,7 +4015,7 @@ class TypeObject implements Type { } async getThisType(): Promise { - return this.objectRegistry.fetchOptionalType(this, "getThisTypeOfType", this.thisType) as Promise; + return this.objectRegistry.fetchOptionalType(this, "getThisTypeOfType", this.thisType); } async getAliasTypeArguments(): Promise { diff --git a/packages/typescript/src/api/async/client.ts b/packages/typescript/src/api/async/client.ts index d91cb099b2669..7549f8e92ecf5 100644 --- a/packages/typescript/src/api/async/client.ts +++ b/packages/typescript/src/api/async/client.ts @@ -109,7 +109,7 @@ class RpcClient { const { spawn } = nodeProcess().getBuiltinModule("node:child_process"); return new Promise((resolve, reject) => { - const args = getAPIProcessArgs(options, true); + const args = getAPIProcessArgs(options, /*async*/ true); const fsConfiguration = configureFileSystemCallbacks(options.fs); if (fsConfiguration.arguments.length > 0) { @@ -255,7 +255,7 @@ class RpcClient { method: requestType.method, roundTripMs, bytesSent, - bytesReceived: result === undefined || result === null + bytesReceived: result == undefined ? 0 : Buffer.byteLength(JSON.stringify(result), "utf-8"), }); @@ -406,7 +406,7 @@ class RpcClient { if (this.connected && this.connection) { // Keep the server's collection in sync so combined totals stay meaningful. const requestType = this.requestType("resetServerTiming"); - await this.connection.sendRequest(requestType, undefined); + await this.connection.sendRequest(requestType, /*params*/ undefined); } } @@ -417,7 +417,7 @@ class RpcClient { // Fetch the server's own timing collection via a dedicated request. This // bypasses the client-side collector so the query does not pollute it. const requestType = this.requestType("getServerTiming"); - return this.connection.sendRequest(requestType, undefined); + return this.connection.sendRequest(requestType, /*params*/ undefined); } close(): Promise { diff --git a/packages/typescript/src/api/async/jsonrpc.ts b/packages/typescript/src/api/async/jsonrpc.ts index 22ed6311ade91..80fff59d81692 100644 --- a/packages/typescript/src/api/async/jsonrpc.ts +++ b/packages/typescript/src/api/async/jsonrpc.ts @@ -45,9 +45,12 @@ interface EventSource { off(event: string, listener: (...args: any[]) => void): unknown; } +// eslint-disable-next-line no-restricted-syntax -- Node writable callbacks may use null for no error. +type WriteCallback = (error: Error | null | undefined) => void; + interface WritableStream extends EventSource { - write(data: Uint8Array, callback: (error: Error | null | undefined) => void): unknown; - write(data: string, encoding: RAL.MessageBufferEncoding, callback: (error: Error | null | undefined) => void): unknown; + write(data: Uint8Array, callback: WriteCallback): unknown; + write(data: string, encoding: RAL.MessageBufferEncoding, callback: WriteCallback): unknown; end(): unknown; } @@ -114,7 +117,7 @@ export function createStreamConnection(readable: EventSource, writable: Writable onEnd: listener => listen(writable, "end", listener), write: (data: Uint8Array | string, encoding?: RAL.MessageBufferEncoding) => new Promise((resolve, reject) => { - const callback = (error: Error | null | undefined) => error ? reject(error) : resolve(); + const callback: WriteCallback = error => error ? reject(error) : resolve(); if (typeof data === "string") { writable.write(data, encoding ?? "utf-8", callback); } diff --git a/packages/typescript/src/api/async/transportClient.ts b/packages/typescript/src/api/async/transportClient.ts index a99188afb77e9..d73e78ae72512 100644 --- a/packages/typescript/src/api/async/transportClient.ts +++ b/packages/typescript/src/api/async/transportClient.ts @@ -208,7 +208,7 @@ export class TransportClient { if (this.maxResponseBytesPerPage !== undefined) { params.maxResponseBytesPerPage = this.maxResponseBytesPerPage; } - const response = await this.sendRequest("batchRequests", params) as BatchRequestsResponse; + const response: BatchRequestsResponse = await this.sendRequest("batchRequests", params); let responses = response.responses; let continuationToken = response.continuationToken; while (continuationToken) { @@ -219,7 +219,7 @@ export class TransportClient { if (this.maxResponseBytesPerPage !== undefined) { pageParams.maxResponseBytesPerPage = this.maxResponseBytesPerPage; } - const page = await this.sendRequest("batchRequests", pageParams) as BatchRequestsResponse; + const page: BatchRequestsResponse = await this.sendRequest("batchRequests", pageParams); responses = responses.concat(page.responses); continuationToken = page.continuationToken; } @@ -266,7 +266,7 @@ export class TransportClient { this.recordTiming(method, start, response.bytesSent, response.bytesReceived); return response.value.length ? JSON.parse(response.value) as APIMethodInfo[K]["result"] - : undefined as APIMethodInfo[K]["result"]; + : undefined; } private async sendBinaryRequest(method: SourceFileResponseMethod, payload: Uint8Array): Promise { @@ -309,8 +309,7 @@ export class TransportClient { function isPromiseLike(value: unknown): value is PromiseLike { return ( - (typeof value === "object" && value !== null || typeof value === "function") - && "then" in value - && typeof value.then === "function" + (typeof value === "object" && value != undefined || typeof value === "function") + && typeof (value as { then: unknown; }).then === "function" ); } diff --git a/packages/typescript/src/api/fsCallbacks.ts b/packages/typescript/src/api/fsCallbacks.ts index a5b5790f31ebf..3a38a4eb1fd52 100644 --- a/packages/typescript/src/api/fsCallbacks.ts +++ b/packages/typescript/src/api/fsCallbacks.ts @@ -18,11 +18,11 @@ export const serverFS: { /** Panic if the configured operation, or current callback invocation, reaches the server filesystem. */ readonly error: typeof error; } = { - useOS: useOS, - identity: identity, - fakeStat: fakeStat, - noop: noop, - error: error, + useOS, + identity, + fakeStat, + noop, + error, }; type ServerFSSentinelName = keyof typeof serverFS; @@ -111,7 +111,7 @@ export function encodeFileSystemCallbackResult( valid = typeof result === "boolean"; break; case "getAccessibleEntries": { - const entries = result as { files?: unknown; directories?: unknown; symlinks?: unknown; } | null; + const entries = (result ?? undefined) as { files?: unknown; directories?: unknown; symlinks?: unknown; } | undefined; valid = !!entries && isStringArray(entries.files) && isStringArray(entries.directories) diff --git a/packages/typescript/src/api/node/encoder.ts b/packages/typescript/src/api/node/encoder.ts index 776e760cba534..e828da9bccc22 100644 --- a/packages/typescript/src/api/node/encoder.ts +++ b/packages/typescript/src/api/node/encoder.ts @@ -103,7 +103,7 @@ function getChildrenPropertyMask(node: Node): number { // This matches the Go encoder's behavior where non-nil NodeLists (even empty) // are treated as present, and only nil NodeLists are absent. function isChildPresent(v: unknown): boolean { - if (v === undefined || v === null) return false; + if (v == undefined) return false; return true; } @@ -235,7 +235,6 @@ export function encodeNode(node: Node, onNodeEncoded?: (node: Node, index: numbe ); onNodeEncoded?.(node, currentIndex); const saveParentIndex = parentIndex; - const savePrevIndex = prevIndex; parentIndex = currentIndex; prevIndex = 0; @@ -287,7 +286,7 @@ export function encodeNode(node: Node, onNodeEncoded?: (node: Node, index: numbe for (const propName of props) { if (propName === undefined) continue; const child = n[propName]; - if (child === undefined || child === null) continue; + if (child == undefined) continue; if (isNodeArray(child)) { visitNodeList(child); } @@ -383,7 +382,7 @@ const nodeBuffer = (globalThis as { /** * Encode a Uint8Array to a base64 string. */ -export const uint8ArrayToBase64: (data: Uint8Array) => string = "toBase64" in Uint8Array.prototype +export const uint8ArrayToBase64: (data: Uint8Array) => string = !!(Uint8Array.prototype as Uint8Array & { toBase64?: unknown; }).toBase64 ? data => (data as Uint8Array & { toBase64(): string; }).toBase64() : nodeBuffer ? data => nodeBuffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64") @@ -395,7 +394,7 @@ export const uint8ArrayToBase64: (data: Uint8Array) => string = "toBase64" in Ui return btoa(binary); }; -const base64ToUint8Array: (data: string) => Uint8Array = "fromBase64" in Uint8Array +const base64ToUint8Array: (data: string) => Uint8Array = !!(Uint8Array as typeof Uint8Array & { fromBase64?: unknown; }).fromBase64 ? (Uint8Array as unknown as { fromBase64(data: string): Uint8Array; }).fromBase64 : nodeBuffer ? data => { @@ -404,6 +403,7 @@ const base64ToUint8Array: (data: string) => Uint8Array = "fromBase64" in Uint8Ar } : data => Uint8Array.from(atob(data), character => character.charCodeAt(0)); +// eslint-disable-next-line no-restricted-syntax -- A missing source-file response can be null on the wire. export function sourceFileResponseToUint8Array(response: { readonly data: string; } | null | undefined): Uint8Array | undefined { return response ? base64ToUint8Array(response.data) : undefined; } diff --git a/packages/typescript/src/api/node/msgpack.ts b/packages/typescript/src/api/node/msgpack.ts index b5da5f0e1890b..3177e39517a12 100644 --- a/packages/typescript/src/api/node/msgpack.ts +++ b/packages/typescript/src/api/node/msgpack.ts @@ -163,12 +163,12 @@ export class MsgpackReader { const byte = this.buf[this.pos++]; if ((byte & 0xf0) === 0x90) return byte & 0x0f; if (byte === 0xdc) { - const len = this.view.getUint16(this.pos, false); + const len = this.view.getUint16(this.pos, /*littleEndian*/ false); this.pos += 2; return len; } if (byte === 0xdd) { - const len = this.view.getUint32(this.pos, false); + const len = this.view.getUint32(this.pos, /*littleEndian*/ false); this.pos += 4; return len; } @@ -180,12 +180,12 @@ export class MsgpackReader { if (byte <= 0x7f) return byte; if (byte === 0xcc) return this.buf[this.pos++]; if (byte === 0xcd) { - const val = this.view.getUint16(this.pos, false); + const val = this.view.getUint16(this.pos, /*littleEndian*/ false); this.pos += 2; return val; } if (byte === 0xce) { - const val = this.view.getUint32(this.pos, false); + const val = this.view.getUint32(this.pos, /*littleEndian*/ false); this.pos += 4; return val; } @@ -202,11 +202,11 @@ export class MsgpackReader { len = this.buf[this.pos++]; } else if (byte === 0xda) { - len = this.view.getUint16(this.pos, false); + len = this.view.getUint16(this.pos, /*littleEndian*/ false); this.pos += 2; } else if (byte === 0xdb) { - len = this.view.getUint32(this.pos, false); + len = this.view.getUint32(this.pos, /*littleEndian*/ false); this.pos += 4; } else { diff --git a/packages/typescript/src/api/node/node.infrastructure.ts b/packages/typescript/src/api/node/node.infrastructure.ts index 70bc8546c3f55..7e051afd83a4e 100644 --- a/packages/typescript/src/api/node/node.infrastructure.ts +++ b/packages/typescript/src/api/node/node.infrastructure.ts @@ -1,7 +1,6 @@ import { type FileReference, type Node, - type PathKey, SyntaxKind, } from "../../ast/index.ts"; export { modifierToFlag } from "../../ast/modifiers.ts"; @@ -77,10 +76,10 @@ export interface SourceFileInfo { * Read the 128-bit content hash from a source file binary response as a hex string. */ export function readSourceFileHash(data: DataView): string { - const lo0 = data.getUint32(HEADER_OFFSET_HASH_LO0, true); - const lo1 = data.getUint32(HEADER_OFFSET_HASH_LO1, true); - const hi0 = data.getUint32(HEADER_OFFSET_HASH_HI0, true); - const hi1 = data.getUint32(HEADER_OFFSET_HASH_HI1, true); + const lo0 = data.getUint32(HEADER_OFFSET_HASH_LO0, /*littleEndian*/ true); + const lo1 = data.getUint32(HEADER_OFFSET_HASH_LO1, /*littleEndian*/ true); + const hi0 = data.getUint32(HEADER_OFFSET_HASH_HI0, /*littleEndian*/ true); + const hi1 = data.getUint32(HEADER_OFFSET_HASH_HI1, /*littleEndian*/ true); return hex8(hi1) + hex8(hi0) + hex8(lo1) + hex8(lo0); } @@ -90,11 +89,11 @@ export function readSourceFileHash(data: DataView): string { * allowing the client to distinguish files parsed with different options. */ export function readParseOptionsKey(data: DataView): string { - return data.getUint32(HEADER_OFFSET_PARSE_OPTIONS, true).toString(); + return data.getUint32(HEADER_OFFSET_PARSE_OPTIONS, /*littleEndian*/ true).toString(); } export function readSourceFileLease(data: DataView): number { - const lease = data.getBigUint64(HEADER_OFFSET_SOURCE_FILE_LEASE, true); + const lease = data.getBigUint64(HEADER_OFFSET_SOURCE_FILE_LEASE, /*littleEndian*/ true); if (lease === 0n) { throw new Error("Source file response has no lease"); } @@ -105,7 +104,7 @@ export function readSourceFileLease(data: DataView): number { } export function readSourceFileNodeId(data: DataView): string { - const nodeId = data.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, true); + const nodeId = data.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, /*littleEndian*/ true); if (nodeId === 0n) { throw new Error("Source file response has no node ID"); } @@ -134,27 +133,27 @@ export class RemoteNodeBase { } get kind(): SyntaxKind { - return this.view.getUint32(this._byteIndex + NODE_OFFSET_KIND, true); + return this.view.getUint32(this._byteIndex + NODE_OFFSET_KIND, /*littleEndian*/ true); } get pos(): number { - return this.view.getInt32(this._byteIndex + NODE_OFFSET_POS, true); + return this.view.getInt32(this._byteIndex + NODE_OFFSET_POS, /*littleEndian*/ true); } get end(): number { - return this.view.getInt32(this._byteIndex + NODE_OFFSET_END, true); + return this.view.getInt32(this._byteIndex + NODE_OFFSET_END, /*littleEndian*/ true); } get next(): number { - return this.view.getUint32(this._byteIndex + NODE_OFFSET_NEXT, true); + return this.view.getUint32(this._byteIndex + NODE_OFFSET_NEXT, /*littleEndian*/ true); } protected get parentIndex(): number { - return this.view.getUint32(this._byteIndex + NODE_OFFSET_PARENT, true); + return this.view.getUint32(this._byteIndex + NODE_OFFSET_PARENT, /*littleEndian*/ true); } protected get data(): number { - return this.view.getUint32(this._byteIndex + NODE_OFFSET_DATA, true); + return this.view.getUint32(this._byteIndex + NODE_OFFSET_DATA, /*littleEndian*/ true); } protected get dataType(): NodeDataType { diff --git a/packages/typescript/src/api/node/node.ts b/packages/typescript/src/api/node/node.ts index 77f2c9366fcd8..c54b728cf3550 100644 --- a/packages/typescript/src/api/node/node.ts +++ b/packages/typescript/src/api/node/node.ts @@ -11,7 +11,6 @@ import { SpanMapFeature, SpanMapKind, SyntaxKind, - TokenFlags, } from "../../ast/index.ts"; import type { API as AsyncAPI } from "../async/api.ts"; import { tryPathKeyFromCanonical } from "../path.ts"; @@ -116,14 +115,14 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { api?: AsyncAPI | SyncAPI | undefined, ) { const view = new DataView(data.buffer, data.byteOffset, data.byteLength); - const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, true); + const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, /*littleEndian*/ true); super(view, 1, undefined!, undefined!, offsetNodes); this._sourceFile = this; this._offsetNodes = offsetNodes; - this._offsetStringTableOffsets = view.getUint32(HEADER_OFFSET_STRING_TABLE_OFFSETS, true); - this._offsetStringTable = view.getUint32(HEADER_OFFSET_STRING_TABLE, true); - this._offsetExtendedData = view.getUint32(HEADER_OFFSET_EXTENDED_DATA, true); - this._offsetStructuredData = view.getUint32(HEADER_OFFSET_STRUCTURED_DATA, true); + this._offsetStringTableOffsets = view.getUint32(HEADER_OFFSET_STRING_TABLE_OFFSETS, /*littleEndian*/ true); + this._offsetStringTable = view.getUint32(HEADER_OFFSET_STRING_TABLE, /*littleEndian*/ true); + this._offsetExtendedData = view.getUint32(HEADER_OFFSET_EXTENDED_DATA, /*littleEndian*/ true); + this._offsetStructuredData = view.getUint32(HEADER_OFFSET_STRUCTURED_DATA, /*littleEndian*/ true); this._decoder = decoder; this._timing = timing; this.api = api; @@ -156,7 +155,7 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { */ get handleFileKey(): string { if (this._handleFileKey === undefined) { - const nodeId = this.view.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, true); + const nodeId = this.view.getBigUint64(HEADER_OFFSET_SOURCE_FILE_ID, /*littleEndian*/ true); if (nodeId === 0n) { throw new Error("Node has no server source-file identity"); } @@ -223,12 +222,12 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { // container; skip those to mirror normal traversal, where list elements take the // list's parent. The walk terminates at the source file, which occupies index 1 // and is already cached. - let parentIndex = this.view.getUint32(this._offsetNodes + index * NODE_LEN + NODE_OFFSET_PARENT, true); + let parentIndex = this.view.getUint32(this._offsetNodes + index * NODE_LEN + NODE_OFFSET_PARENT, /*littleEndian*/ true); while ( parentIndex !== index && - this.view.getUint32(this._offsetNodes + parentIndex * NODE_LEN + NODE_OFFSET_KIND, true) === KIND_NODE_LIST + this.view.getUint32(this._offsetNodes + parentIndex * NODE_LEN + NODE_OFFSET_KIND, /*littleEndian*/ true) === KIND_NODE_LIST ) { - parentIndex = this.view.getUint32(this._offsetNodes + parentIndex * NODE_LEN + NODE_OFFSET_PARENT, true); + parentIndex = this.view.getUint32(this._offsetNodes + parentIndex * NODE_LEN + NODE_OFFSET_PARENT, /*littleEndian*/ true); } const parent = parentIndex === index ? this : this.getOrCreateNodeAtIndex(parentIndex) as RemoteNode; node = new RemoteNode(this.view, index, parent, this, this._offsetNodes); @@ -257,26 +256,26 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { } get fileName(): RootedFilePath { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.FileName, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.FileName, /*littleEndian*/ true); return this.getFileName(stringIndex); } get path(): PathKey { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.Path, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.Path, /*littleEndian*/ true); return this.getPathKey(stringIndex); } get languageVariant(): number { - return this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.LanguageVariant, true); + return this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.LanguageVariant, /*littleEndian*/ true); } get scriptKind(): number { - return this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ScriptKind, true); + return this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ScriptKind, /*littleEndian*/ true); } get referencedFiles(): readonly FileReference[] { if (this._cachedReferencedFiles !== undefined) return this._cachedReferencedFiles; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ReferencedFiles, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ReferencedFiles, /*littleEndian*/ true); const files = this.readFileReferences(offset); this._cachedReferencedFiles = files; return files; @@ -284,7 +283,7 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get typeReferenceDirectives(): readonly FileReference[] { if (this._cachedTypeReferenceDirectives !== undefined) return this._cachedTypeReferenceDirectives; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.TypeReferenceDirectives, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.TypeReferenceDirectives, /*littleEndian*/ true); const directives = this.readFileReferences(offset); this._cachedTypeReferenceDirectives = directives; return directives; @@ -292,7 +291,7 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get libReferenceDirectives(): readonly FileReference[] { if (this._cachedLibReferenceDirectives !== undefined) return this._cachedLibReferenceDirectives; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.LibReferenceDirectives, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.LibReferenceDirectives, /*littleEndian*/ true); const directives = this.readFileReferences(offset); this._cachedLibReferenceDirectives = directives; return directives; @@ -300,7 +299,7 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get imports(): readonly Node[] { if (this._cachedImports !== undefined) return this._cachedImports; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.Imports, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.Imports, /*littleEndian*/ true); const imports = this.readNodeIndexArray(offset); this._cachedImports = imports; return imports; @@ -308,7 +307,7 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get moduleAugmentations(): readonly Node[] { if (this._cachedModuleAugmentations !== undefined) return this._cachedModuleAugmentations; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ModuleAugmentations, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ModuleAugmentations, /*littleEndian*/ true); const moduleAugmentations = this.readNodeIndexArray(offset); this._cachedModuleAugmentations = moduleAugmentations; return moduleAugmentations; @@ -316,28 +315,28 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get ambientModuleNames(): readonly string[] { if (this._cachedAmbientModuleNames !== undefined) return this._cachedAmbientModuleNames; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.AmbientModuleNames, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.AmbientModuleNames, /*littleEndian*/ true); const names = this.readStringArray(offset); this._cachedAmbientModuleNames = names; return names; } get externalModuleIndicator(): Node | true | undefined { - const nodeIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ExternalModuleIndicator, true); + const nodeIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ExternalModuleIndicator, /*littleEndian*/ true); if (nodeIndex === 0) return undefined; if (nodeIndex === this.index) return true; - return this.getOrCreateNodeAtIndex(nodeIndex) as Node; + return this.getOrCreateNodeAtIndex(nodeIndex); } get originalText(): string { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.OriginalText, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.OriginalText, /*littleEndian*/ true); return this.getString(stringIndex); } get spanMap(): SpanMap | undefined { if (this._spanMapRead) return this._cachedSpanMap; this._spanMapRead = true; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.SpanMap, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.SpanMap, /*littleEndian*/ true); if (offset === NO_STRUCTURED_DATA) return undefined; const buf = new Uint8Array(this.view.buffer, this.view.byteOffset, this.view.byteLength); const reader = new MsgpackReader(buf, this._offsetStructuredData + offset); @@ -367,30 +366,30 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get supplementalSourceFileNames(): readonly RootedFilePath[] | undefined { if (this._cachedSupplementalSourceFileNames !== undefined) return this._cachedSupplementalSourceFileNames; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.SupplementalSourceFileNames, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.SupplementalSourceFileNames, /*littleEndian*/ true); if (offset === NO_STRUCTURED_DATA) return undefined; return this._cachedSupplementalSourceFileNames = this.readFileNameArray(offset); } get canonicalSourceFileName(): RootedFilePath | undefined { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.CanonicalSourceFileName, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.CanonicalSourceFileName, /*littleEndian*/ true); return stringIndex === NO_STRUCTURED_DATA ? undefined : this.getFileName(stringIndex); } get contentMapper(): string | undefined { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ContentMapper, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.ContentMapper, /*littleEndian*/ true); return stringIndex === NO_STRUCTURED_DATA ? undefined : this.getString(stringIndex); } get virtualFileName(): RootedFilePath | undefined { - const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.VirtualFileName, true); + const stringIndex = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.VirtualFileName, /*littleEndian*/ true); return stringIndex === NO_STRUCTURED_DATA ? undefined : this.getFileName(stringIndex); } get diagnosticDirectives(): readonly MappedDiagnosticDirective[] | undefined { if (this._diagnosticDirectivesRead) return this._cachedDiagnosticDirectives; this._diagnosticDirectivesRead = true; - const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.DiagnosticDirectives, true); + const offset = this.view.getUint32(this.extendedDataOffset + sourceFileExtendedDataOffsets.DiagnosticDirectives, /*littleEndian*/ true); if (offset === NO_STRUCTURED_DATA) return undefined; const buf = new Uint8Array(this.view.buffer, this.view.byteOffset, this.view.byteLength); const reader = new MsgpackReader(buf, this._offsetStructuredData + offset); @@ -532,7 +531,7 @@ export function parseNodeHandleFromCompiler(handle: string): ParsedNodeHandle { !Number.isSafeInteger(kind) || kind < 0 || String(kind) !== kindText || - !/^#[1-9][0-9]*$/.test(fileKey) || + !/^#[1-9]\d*$/.test(fileKey) || BigInt(sourceFileId) > 0xFFFFFFFFFFFFFFFFn || key === undefined ) { @@ -540,7 +539,7 @@ export function parseNodeHandleFromCompiler(handle: string): ParsedNodeHandle { } return { index, - kind: kind as SyntaxKind, + kind, sourceFileId, path: key, }; @@ -553,7 +552,7 @@ export function parseNodeHandleFromCompiler(handle: string): ParsedNodeHandle { */ export function decodeNode(data: Uint8Array): Node { const sf = new RemoteSourceFile(data, new Wtf8Decoder()); - return sf as unknown as Node; + return sf; } /** diff --git a/packages/typescript/src/api/node/wtf8.ts b/packages/typescript/src/api/node/wtf8.ts index f73ac298e35f6..afd5e60757bed 100644 --- a/packages/typescript/src/api/node/wtf8.ts +++ b/packages/typescript/src/api/node/wtf8.ts @@ -7,6 +7,7 @@ const textEncoder = new TextEncoder(); const replacementCharacterUtf8 = new Uint8Array([0xEF, 0xBF, 0xBD]); const loneSurrogateRegExp = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/; const shortStringLength = 64; +// eslint-disable-next-line no-restricted-syntax -- The decoder accepts null as empty input. type DecodeInput = ArrayBufferView | ArrayBufferLike | null; interface DecodeOptions { stream?: boolean | undefined; @@ -38,7 +39,7 @@ function hasReplacementCharacter(bytes: Uint8Array): boolean { return false; } -function toUint8Array(input: Exclude): Uint8Array { +function toUint8Array(input: NonNullable): Uint8Array { if (input instanceof Uint8Array) { return input; } @@ -120,8 +121,8 @@ export function encodeWtf8(text: string): Uint8Array { export class Wtf8Decoder extends TextDecoder { override decode(input?: DecodeInput, options?: DecodeOptions): string { - if (input == null) { - return super.decode(undefined, options); + if (input == undefined) { + return super.decode(/*input*/ undefined, options); } const bytes = toUint8Array(input); diff --git a/packages/typescript/src/api/options.ts b/packages/typescript/src/api/options.ts index 6f00544421f84..046e8a2f16694 100644 --- a/packages/typescript/src/api/options.ts +++ b/packages/typescript/src/api/options.ts @@ -46,7 +46,7 @@ export interface ClientSpawnOptions { export type ClientOptions = ClientSocketOptions | ClientSpawnOptions; export function isSpawnOptions(options: ClientOptions): options is ClientSpawnOptions { - return !("pipe" in options); + return !(options as ClientSocketOptions).pipe; } interface TransportOptionsBase { @@ -70,7 +70,7 @@ export interface ClientTransportOptions extends TransportOptionsBase { export type SyncClientOptions = ClientSocketOptions | ClientSpawnOptions | ClientTransportOptions; export function isTransportOptions(options: T): options is Extract { - return "transport" in options; + return !!(options as { transport?: unknown; }).transport; } export interface AsyncClientTransportOptions extends TransportOptionsBase { diff --git a/packages/typescript/src/api/path.ts b/packages/typescript/src/api/path.ts index e692cdf1b3833..a1c7ea7897def 100644 --- a/packages/typescript/src/api/path.ts +++ b/packages/typescript/src/api/path.ts @@ -809,7 +809,7 @@ export function documentURIToFileName(uri: string): string { let encodedAuthority = authority; if (hasAuthority) { encodedAuthority = authority === "ts-nul-authority" - ? forceEncodeDynamicURIPathSegment(authority, false) + ? forceEncodeDynamicURIPathSegment(authority, /*preserveExtension*/ false) : encodeDynamicURIPath(authority); } const encodedPath = hasPath @@ -839,7 +839,7 @@ function encodeDynamicURIPathWithSuffix(path: string, suffix: string): string { return encodeDynamicURIPath(path); } const slash = path.lastIndexOf("/"); - const before = slash === -1 ? "" : encodeDynamicURIPath(path.substring(0, slash), false) + "/"; + const before = slash === -1 ? "" : encodeDynamicURIPath(path.substring(0, slash), /*preserveFinalExtension*/ false) + "/"; return before + forceEncodeDynamicURIPathSegmentWithSuffix(path.substring(slash + 1), suffix); } @@ -890,7 +890,7 @@ function forceEncodeDynamicURIPathSegment(segment: string, preserveExtension: bo function forceEncodeDynamicURIPathSegmentWithSuffix(segment: string, suffix: string): string { const [base, extension] = splitDynamicURIFileExtension(segment); - return forceEncodeDynamicURIPathSegment(base + "\0" + suffix, false) + extension; + return forceEncodeDynamicURIPathSegment(base + "\0" + suffix, /*preserveExtension*/ false) + extension; } function splitDynamicURIFileExtension(segment: string): [base: string, extension: string] { diff --git a/packages/typescript/src/api/printer.ts b/packages/typescript/src/api/printer.ts index 8f80d12342d8a..c5e2ccc986cc8 100644 --- a/packages/typescript/src/api/printer.ts +++ b/packages/typescript/src/api/printer.ts @@ -24,7 +24,6 @@ export interface SynthesizedComment { hasLeadingNewLine: boolean; } -/** @internal */ interface EmitNode { emitFlags: EmitFlags; leadingComments: SynthesizedComment[] | undefined; @@ -83,7 +82,7 @@ export function createEmitContext(): EmitContext { return node; }, getEmitFlags(node) { - return emitNodes.get(node)?.emitFlags ?? 0 as EmitFlags; + return emitNodes.get(node)?.emitFlags ?? 0; }, addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine, hasLeadingNewLine) { diff --git a/packages/typescript/src/api/proto.ts b/packages/typescript/src/api/proto.ts index 0d2b767f8bac6..be0a5b2d8c32d 100644 --- a/packages/typescript/src/api/proto.ts +++ b/packages/typescript/src/api/proto.ts @@ -81,6 +81,7 @@ export type APIResponse = Request exten result: APIMethodInfo[Request["method"]]["result"]; error?: undefined; } | { + // eslint-disable-next-line no-restricted-syntax -- Failed batch responses carry a null result. result: null; error: string; }) : @@ -107,8 +108,8 @@ export function resolveFileName(identifier: DocumentIdentifier): string { if (typeof identifier === "string") { return identifier; } - if (typeof identifier !== "object" || identifier === null || typeof identifier.uri !== "string") { - const received = typeof identifier === "object" && identifier !== null + if (typeof identifier !== "object" || identifier == undefined || typeof identifier.uri !== "string") { + const received = typeof identifier === "object" && identifier != undefined ? `an object with keys: ${Object.keys(identifier).join(", ")}` : String(identifier); throw new TypeError(`Expected a string or { uri } for the document, received ${received}`); @@ -130,5 +131,6 @@ export function resolveDocumentURI(identifier: DocumentIdentifier): string { export type CreateSnapshotParams = CoreCreateSnapshotParams; export interface CreateBuildOrchestratorParams { + // eslint-disable-next-line no-restricted-syntax -- The protocol permits a null rootNames list. rootNames: readonly string[] | null; } diff --git a/packages/typescript/src/api/sourceFileCache.ts b/packages/typescript/src/api/sourceFileCache.ts index 73a8360165a38..98fa7d3b13082 100644 --- a/packages/typescript/src/api/sourceFileCache.ts +++ b/packages/typescript/src/api/sourceFileCache.ts @@ -290,7 +290,8 @@ export class SourceFileCache { for (let i = entries.length - 1; i >= 0; i--) { entries[i].refs.delete(ref); if (entries[i].refs.size === 0) { - const [evicted] = entries.splice(i, 1); + const evicted = entries[i]; + entries.splice(i, 1); if (this.recordsByNodeId.get(evicted.descriptor.nodeId) === evicted) { this.recordsByNodeId.delete(evicted.descriptor.nodeId); } diff --git a/packages/typescript/src/api/sync/api.ts b/packages/typescript/src/api/sync/api.ts index b40ce9ffc272b..e4bd14c71e004 100644 --- a/packages/typescript/src/api/sync/api.ts +++ b/packages/typescript/src/api/sync/api.ts @@ -78,8 +78,6 @@ import { getNodeId, getNodeRequestHandle, parseNodeHandleFromCompiler, - readParseOptionsKey, - readSourceFileHash, readSourceFileLease, RemoteNode, RemoteSourceFile, @@ -117,7 +115,6 @@ import type { CreateSnapshotResponse, CreateSourceFileOptions, Diagnostic, - DiagnosticResponse, DocumentIdentifier, DocumentPosition, EmitOutputResponse as ProtocolEmitOutputResponse, @@ -171,7 +168,6 @@ import { import type { RequestTiming, TimingAccumulators, - TimingCollector, TimingInfo, } from "../timing.ts"; import { @@ -555,7 +551,8 @@ export class API implements FormatDiagnosticsHo "initializeWorker", function (): void { try { - const response = owner.client.apiRequest("initialize", null); + // eslint-disable-next-line no-restricted-syntax -- The initialize request requires null parameters. + const response = owner.client.apiRequest("initialize", /*params*/ null); owner.currentDirectory = response.currentDirectory; owner.caseSensitivity = response.caseSensitivity; owner.toPath = (fileName: string, basePath = response.currentDirectory) => pathKey(toRootedPath(fileName, toRootedDirectoryPath(basePath, response.currentDirectory)), response.caseSensitivity); @@ -568,6 +565,7 @@ export class API implements FormatDiagnosticsHo }, function* (): Generator { try { + // eslint-disable-next-line no-restricted-syntax -- The initialize request requires null parameters. const response = yield* apiRequest("initialize", null); owner.currentDirectory = response.currentDirectory; owner.caseSensitivity = response.caseSensitivity; @@ -991,7 +989,7 @@ export class API implements FormatDiagnosticsHo owner.sourceFileCache.releaseSnapshot(snapshot.id); }, owner.createSnapshotUpdater(() => snapshot), - undefined, + /*baseSnapshot*/ undefined, ); owner.activeSnapshots.set(snapshot.id, snapshot); @@ -1014,7 +1012,7 @@ export class API implements FormatDiagnosticsHo owner.sourceFileCache.releaseSnapshot(snapshot.id); }, owner.createSnapshotUpdater(() => snapshot), - undefined, + /*baseSnapshot*/ undefined, ); owner.activeSnapshots.set(snapshot.id, snapshot); @@ -1161,8 +1159,8 @@ export class API implements FormatDiagnosticsHo function getCurrentLanguageServerSnapshot(...args: FromLSP extends true ? [changes?: LanguageServerSnapshotChanges, baseSnapshot?: Snapshot] : [changes: never, baseSnapshot?: never]): Snapshot { owner.ensureInitialized(); - const changes = args[0] as LanguageServerSnapshotChanges | undefined; - const baseSnapshot = args[1] as Snapshot | undefined; + const changes = args[0]; + const baseSnapshot = args[1]; if (baseSnapshot && (owner.activeSnapshots.get(baseSnapshot.id) !== baseSnapshot || baseSnapshot.isDisposed())) { throw new Error("Cannot use an inactive snapshot as a response base"); } @@ -1195,8 +1193,8 @@ export class API implements FormatDiagnosticsHo function* gen(...args: FromLSP extends true ? [changes?: LanguageServerSnapshotChanges, baseSnapshot?: Snapshot] : [changes: never, baseSnapshot?: never]): Generator { yield* owner.ensureInitialized.gen(); - const changes = args[0] as LanguageServerSnapshotChanges | undefined; - const baseSnapshot = args[1] as Snapshot | undefined; + const changes = args[0]; + const baseSnapshot = args[1]; if (baseSnapshot && (owner.activeSnapshots.get(baseSnapshot.id) !== baseSnapshot || baseSnapshot.isDisposed())) { throw new Error("Cannot use an inactive snapshot as a response base"); } @@ -1446,7 +1444,7 @@ export class API implements FormatDiagnosticsHo const snapshot = owner.createSnapshot({ createPrograms: [{ rootFiles, compilerOptions, options: createProgramOptions }], }); - const program = snapshot.operation.createdPrograms![0]; + const program = snapshot.operation.createdPrograms[0]; if (!program) { snapshot.dispose(); throw new Error("createProgram did not return a project"); @@ -1460,7 +1458,7 @@ export class API implements FormatDiagnosticsHo const snapshot = yield* owner.createSnapshot.gen({ createPrograms: [{ rootFiles, compilerOptions, options: createProgramOptions }], }); - const program = snapshot.operation.createdPrograms![0]; + const program = snapshot.operation.createdPrograms[0]; if (!program) { yield* snapshot.dispose.gen(); throw new Error("createProgram did not return a project"); @@ -1628,11 +1626,13 @@ export class DebugHandlers { "stopCPUProfile", function (): RootedFilePath { owner.ensureInitialized(); - const result = owner.client.apiRequest("stopCPUProfile", null); + // eslint-disable-next-line no-restricted-syntax -- The stopCPUProfile request requires null parameters. + const result = owner.client.apiRequest("stopCPUProfile", /*params*/ null); return result.file; }, function* (): Generator { yield* owner.ensureInitialized.gen(); + // eslint-disable-next-line no-restricted-syntax -- The stopCPUProfile request requires null parameters. const result = yield* apiRequest("stopCPUProfile", null); return result.file; }, @@ -2321,7 +2321,7 @@ class ProjectObjectRegistry { project: owner.project.handle, objectId: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; else return typesData.map(data => owner.getOrCreateType(data)); }, function* (source: Symbol | Signature | Type, method: TypesPropertyMethod, handles?: readonly number[]): Generator { @@ -2343,7 +2343,7 @@ class ProjectObjectRegistry { project: owner.project.handle, objectId: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; else return typesData.map(data => owner.getOrCreateType(data)); }, ); @@ -2435,7 +2435,7 @@ class ProjectObjectRegistry { project: owner.project.handle, type: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; return typesData.map(data => owner.getOrCreateType(data)); }, function* (source: Type): Generator { @@ -2444,7 +2444,7 @@ class ProjectObjectRegistry { project: owner.project.handle, type: source.id, }); - if (typesData == null) return []; + if (typesData == undefined) return []; return typesData.map(data => owner.getOrCreateType(data)); }, ); @@ -3564,7 +3564,7 @@ export class Program implements FormatDiagnost return undefined; } - return new RemoteSourceFile(binaryData, owner.decoder, undefined, owner.project.api) as unknown as SourceFile; + return new RemoteSourceFile(binaryData, owner.decoder, /*timing*/ undefined, owner.project.api) as unknown as SourceFile; }, function* (file: DocumentIdentifier): Generator { const binaryData = sourceFileResponseToUint8Array( @@ -3578,7 +3578,7 @@ export class Program implements FormatDiagnost return undefined; } - return new RemoteSourceFile(binaryData, owner.decoder, undefined, owner.project.api) as unknown as SourceFile; + return new RemoteSourceFile(binaryData, owner.decoder, /*timing*/ undefined, owner.project.api) as unknown as SourceFile; }, ); } @@ -4231,6 +4231,10 @@ function encodeNumberLiteralValue(value: number): number | string { return value; } +function isNodeLocation(location: Node | DocumentPosition): location is Node { + return !!(location as Node).kind; +} + export class Checker { /** Get the original symbols underlying a synthetic, instantiated, or mapped property. */ get getRootSymbols(): { @@ -4978,30 +4982,30 @@ export class Checker { "resolveName", function (name: string, meaning: SymbolFlags, location?: Node | DocumentPosition, excludeGlobals?: boolean): Symbol | undefined { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = location && "kind" in location; + const isNode = location && isNodeLocation(location); const data = owner.client.apiRequest("resolveName", { snapshot: owner.snapshotId, project: owner.project.handle, name, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: !isNode && location ? (location as DocumentPosition).document : undefined, - position: !isNode && location ? (location as DocumentPosition).position : undefined, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: !isNode && location ? location.document : undefined, + position: !isNode && location ? location.position : undefined, excludeGlobals, }); return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; }, function* (name: string, meaning: SymbolFlags, location?: Node | DocumentPosition, excludeGlobals?: boolean): Generator { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = location && "kind" in location; + const isNode = location && isNodeLocation(location); const data = yield* apiRequest("resolveName", { snapshot: owner.snapshotId, project: owner.project.handle, name, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: !isNode && location ? (location as DocumentPosition).document : undefined, - position: !isNode && location ? (location as DocumentPosition).position : undefined, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: !isNode && location ? location.document : undefined, + position: !isNode && location ? location.position : undefined, excludeGlobals, }); return data ? owner.objectRegistry.getOrCreateSymbol(data) : undefined; @@ -5022,27 +5026,27 @@ export class Checker { "getSymbolsInScope", function (location: Node | DocumentPosition, meaning: SymbolFlags): readonly Symbol[] { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = "kind" in location; + const isNode = isNodeLocation(location); const data = owner.client.apiRequest("getSymbolsInScope", { snapshot: owner.snapshotId, project: owner.project.handle, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: isNode ? undefined : (location as DocumentPosition).document, - position: isNode ? undefined : (location as DocumentPosition).position, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: isNode ? undefined : location.document, + position: isNode ? undefined : location.position, }); return data ? data.map(d => owner.objectRegistry.getOrCreateSymbol(d)) : []; }, function* (location: Node | DocumentPosition, meaning: SymbolFlags): Generator { // Distinguish Node (has `kind`) from DocumentPosition (has `document` and `position`) - const isNode = "kind" in location; + const isNode = isNodeLocation(location); const data = yield* apiRequest("getSymbolsInScope", { snapshot: owner.snapshotId, project: owner.project.handle, meaning, - location: isNode ? getNodeRequestHandle(location as Node) : undefined, - file: isNode ? undefined : (location as DocumentPosition).document, - position: isNode ? undefined : (location as DocumentPosition).position, + location: isNode ? getNodeRequestHandle(location) : undefined, + file: isNode ? undefined : location.document, + position: isNode ? undefined : location.position, }); return data ? data.map(d => owner.objectRegistry.getOrCreateSymbol(d)) : []; }, @@ -5895,7 +5899,7 @@ export class Checker { flags, }); if (!binaryData) return undefined; - return decodeNode(binaryData) as Node; + return decodeNode(binaryData); }, function* (signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Generator { const binaryData = sourceFileResponseToUint8Array( @@ -5909,7 +5913,7 @@ export class Checker { }), ); if (!binaryData) return undefined; - return decodeNode(binaryData) as Node; + return decodeNode(binaryData); }, ); } @@ -7609,7 +7613,7 @@ export class Symbol { // A file-owned symbol has no canonical project; its declarations resolve through its file. return this.storage.kind === SymbolOwnerKind.Snapshot ? this.storage.registry.createNodeHandle(handle) - : new NodeHandle(handle, undefined, this.storage.owner); + : new NodeHandle(handle, /*canonicalProject*/ undefined, this.storage.owner); } get getParent(): { @@ -7890,12 +7894,13 @@ class TypeObject implements Type { this.flags = data.flags; this.objectFlags = data.objectFlags ?? 0; if (data.symbol !== undefined) this.symbol = data.symbol; - if (data.value != null) { + const typeValue = data.value; + if (typeValue != undefined) { // BigInt literal values are serialized as decimal strings (e.g. "-123") because // JSON cannot represent bigint. Decode them back into a real bigint here. - const value = data.value as string | number | boolean; + const value = typeValue as string | number | boolean; if (data.flags & TypeFlags.BigIntLiteral) { - this.value = BigInt(value as string); + this.value = BigInt(value); } // JSON cannot represent infinities, so the API serializes them as strings. else if (data.flags & TypeFlags.NumberLiteral && typeof value === "string") { @@ -8422,10 +8427,10 @@ class TypeObject implements Type { owner, "getThisType", function (): TypeParameter | undefined { - return owner.objectRegistry.fetchOptionalType(owner, "getThisTypeOfType", owner.thisType) as TypeParameter | undefined; + return owner.objectRegistry.fetchOptionalType(owner, "getThisTypeOfType", owner.thisType); }, function* (): Generator { - return (yield* owner.objectRegistry.fetchOptionalType.gen(owner, "getThisTypeOfType", owner.thisType)) as TypeParameter | undefined; + return yield* owner.objectRegistry.fetchOptionalType.gen(owner, "getThisTypeOfType", owner.thisType); }, ); } diff --git a/packages/typescript/src/api/sync/client.ts b/packages/typescript/src/api/sync/client.ts index d440bc46d4558..0c316df0d815f 100644 --- a/packages/typescript/src/api/sync/client.ts +++ b/packages/typescript/src/api/sync/client.ts @@ -41,7 +41,7 @@ export class Client extends TransportClient { if (timingDump) { options = { ...options, collectTiming: true }; } - const args = getAPIProcessArgs(options, false); + const args = getAPIProcessArgs(options, /*async*/ false); const fsConfiguration = configureFileSystemCallbacks(options.fs); if (fsConfiguration.arguments.length > 0) { args.push(`--callbacks=${fsConfiguration.arguments.join(",")}`); diff --git a/packages/typescript/src/api/sync/generatorSupport.ts b/packages/typescript/src/api/sync/generatorSupport.ts index 0604d816bdb01..ea0f5ef7fee67 100644 --- a/packages/typescript/src/api/sync/generatorSupport.ts +++ b/packages/typescript/src/api/sync/generatorSupport.ts @@ -279,7 +279,7 @@ export function executeRequestGenerators)[allGeneratorMarker]) break; const wrapper = generator as AllRequestGenerator; const pending = wrapper.generators; if (!pending) break; @@ -331,7 +331,7 @@ export function executeRequestGenerators unknown): () => void { diff --git a/packages/typescript/src/api/syncChannel.ts b/packages/typescript/src/api/syncChannel.ts index 92c43c8f5c278..d94f4087e279e 100644 --- a/packages/typescript/src/api/syncChannel.ts +++ b/packages/typescript/src/api/syncChannel.ts @@ -176,7 +176,7 @@ export class SyncRpcChannel { break; } catch { - if (this.child.exitCode !== null) { + if (this.child.exitCode != undefined) { throw new Error( `Child process exited with code ${this.child.exitCode} before pipe was ready`, ); @@ -432,13 +432,13 @@ export class SyncRpcChannel { if (payloadIsString) { // Encode string directly into write buffer — avoids // Buffer.from(string, 'utf-8') allocation entirely. - this.writeBuf.write(payload as string, off, payloadLen, "utf-8"); + this.writeBuf.write(payload, off, payloadLen, "utf-8"); } else if (payload instanceof Buffer) { (payload as Buffer).copy(this.writeBuf, off); } else { - this.writeBuf.set(payload as Uint8Array, off); + this.writeBuf.set(payload, off); } } this.writeAllBuf(this.writeBuf, totalSize); @@ -457,10 +457,10 @@ export class SyncRpcChannel { if (payloadIsString) { // Large string: must allocate (can't stream-encode // across multiple writeSync calls). - this.writeAllBuf(Buffer.from(payload as string, "utf-8")); + this.writeAllBuf(Buffer.from(payload, "utf-8")); } else { - this.writeAllBuf(payload as Buffer | Uint8Array); + this.writeAllBuf(payload); } } } @@ -533,7 +533,7 @@ export class SyncRpcChannel { private eofError(): Error { const code = this.child.exitCode; const signal = this.child.signalCode; - const detail = signal ? `killed by signal ${signal}` : code !== null ? `exited with code ${code}` : "unknown reason"; + const detail = signal ? `killed by signal ${signal}` : code != undefined ? `exited with code ${code}` : "unknown reason"; return new Error(`Unexpected EOF while reading from child process (${detail})`); } @@ -571,7 +571,7 @@ export class SyncRpcChannel { this.readBufLen = 0; for (;;) { try { - const n = this.fs.readSync(this.readFd, this.readBuf, 0, this.readBuf.length, null); + const n = this.fs.readSync(this.readFd, this.readBuf); if (n === 0) { throw this.eofError(); } @@ -579,7 +579,7 @@ export class SyncRpcChannel { return; } catch (e: unknown) { - if (e instanceof Error && ("code" in e) && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { + if (e instanceof Error && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { sleep(1); continue; } @@ -609,14 +609,14 @@ export class SyncRpcChannel { // Remaining data is larger than read buffer; read directly // into the target to avoid unnecessary copying. try { - const n = this.fs.readSync(this.readFd, buffer, pos, length - pos, null); + const n = this.fs.readSync(this.readFd, buffer, { offset: pos, length: length - pos }); if (n === 0) { throw this.eofError(); } pos += n; } catch (e: unknown) { - if (e instanceof Error && ("code" in e) && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { + if (e instanceof Error && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { sleep(1); continue; } @@ -643,7 +643,7 @@ export class SyncRpcChannel { pos += n; } catch (e: unknown) { - if (e instanceof Error && ("code" in e) && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { + if (e instanceof Error && ((e as NodeJS.ErrnoException).code === "EAGAIN" || (e as NodeJS.ErrnoException).code === "EWOULDBLOCK")) { sleep(1); continue; } diff --git a/packages/typescript/src/api/timing.ts b/packages/typescript/src/api/timing.ts index b4d719d4c2869..5f437b3023951 100644 --- a/packages/typescript/src/api/timing.ts +++ b/packages/typescript/src/api/timing.ts @@ -1,4 +1,4 @@ -/** +/* * Client-side collection of per-request timing and transfer measurements. * * When enabled, each request records its round-trip latency and the number of diff --git a/packages/typescript/src/api/timingDump.ts b/packages/typescript/src/api/timingDump.ts index 9f272bf140cfa..055d75a8d9c90 100644 --- a/packages/typescript/src/api/timingDump.ts +++ b/packages/typescript/src/api/timingDump.ts @@ -38,6 +38,7 @@ export class TimingDump { startedAt: this.startedAt, closedAt: new Date().toISOString(), timing: server ? combineTimingInfo(client, server) : client, + // eslint-disable-next-line no-restricted-syntax -- Keep the field present in the JSON dump. serverTiming: server ?? null, serverTimingError, }; diff --git a/packages/typescript/src/ast/astnav.ts b/packages/typescript/src/ast/astnav.ts index 98c67d788e0ac..3bdfc3839d2f6 100644 --- a/packages/typescript/src/ast/astnav.ts +++ b/packages/typescript/src/ast/astnav.ts @@ -798,7 +798,7 @@ function createSyntaxListNode(nodes: NodeArray, parent: Node, sourceFile: list.pos = nodes.pos; list.end = nodes.end; list.parent = parent; - return list as Node; + return list; } export function getFirstToken(node: Node, sourceFile: SourceFile = node.getSourceFile()): Node | undefined { diff --git a/packages/typescript/src/ast/is.ts b/packages/typescript/src/ast/is.ts index c298cb04f8e0a..2441d7af904ab 100644 --- a/packages/typescript/src/ast/is.ts +++ b/packages/typescript/src/ast/is.ts @@ -49,6 +49,7 @@ import type { JSDocTypeExpression, JSDocTypeLiteral, JsxAttributeLike, + JsxClosingElement, JsxExpression, JsxOpeningElement, JsxOpeningFragment, @@ -59,6 +60,7 @@ import type { LiteralExpression, MetaProperty, MinusToken, + ModifiersBase, ModuleDeclaration, NewExpression, Node, @@ -155,7 +157,7 @@ export function isAutoAccessorPropertyDeclaration(node: Node): node is AutoAcces type JSDocNamespaceDeclaration = ModuleDeclaration; -type WrappedExpression = +type WrappedExpression<_T extends Expression> = | ParenthesizedExpression | TypeAssertion | AsExpression @@ -291,7 +293,7 @@ function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node: Node): bo if (!isComputedPropertyName(node)) { return false; } - if (hasModifierFlags(node.parent) && node.parent.modifierFlags & ModifierFlags.Abstract) { + if ((node.parent as ModifiersBase).modifiers?.some(modifier => modifier.kind === SyntaxKind.AbstractKeyword)) { return true; } const containerKind = node.parent.parent.kind; @@ -317,10 +319,6 @@ function findAncestor(node: Node, callback: (node: Node) => AncestorCallbackResu } } -function hasModifierFlags(node: Node): node is Node & { readonly modifierFlags: ModifierFlags; } { - return "modifierFlags" in node; -} - function isExpressionNode(node: Node): boolean { switch (node.kind) { case SyntaxKind.SuperKeyword: @@ -474,16 +472,12 @@ function isJSXTagName(node: Node): boolean { case SyntaxKind.JsxOpeningElement: case SyntaxKind.JsxSelfClosingElement: case SyntaxKind.JsxClosingElement: - return hasTagName(parent) && parent.tagName === node; + return (parent as JsxOpeningElement | JsxSelfClosingElement | JsxClosingElement).tagName === node; default: return false; } } -function hasTagName(node: Node): node is Node & { readonly tagName: Node; } { - return "tagName" in node; -} - export function isBlockOrExpression(node: Node): node is BlockOrExpression { return node.kind === SyntaxKind.Block || isExpression(node); } @@ -744,7 +738,7 @@ export function isIterationStatement(node: Node, lookInLabeledStatements: boolea case SyntaxKind.WhileStatement: return true; case SyntaxKind.LabeledStatement: - return lookInLabeledStatements && isIterationStatement((node as LabeledStatement).statement, true); + return lookInLabeledStatements && isIterationStatement((node as LabeledStatement).statement, /*lookInLabeledStatements*/ true); default: return false; } diff --git a/packages/typescript/src/ast/scanner.ts b/packages/typescript/src/ast/scanner.ts index 0f5c53d94dc59..5bf52589d2911 100644 --- a/packages/typescript/src/ast/scanner.ts +++ b/packages/typescript/src/ast/scanner.ts @@ -790,7 +790,7 @@ export function isIdentifierText(name: string, _languageVersion?: ScriptTarget, } for (let i = charSize(ch); i < name.length; i += charSize(ch)) { - if (!isIdentifierPart(ch = name.codePointAt(i)!, undefined, identifierVariant)) { + if (!isIdentifierPart(ch = name.codePointAt(i)!, /*languageVersion*/ undefined, identifierVariant)) { return false; } } @@ -988,7 +988,6 @@ export function createScanner( function scanNumberFragment(): string { let start = pos; let allowSeparator = false; - let isPreviousTokenSeparator = false; let result = ""; while (true) { const ch = charCodeUnchecked(pos); @@ -996,7 +995,6 @@ export function createScanner( tokenFlags |= TokenFlags.ContainsSeparator; if (allowSeparator) { allowSeparator = false; - isPreviousTokenSeparator = true; result += text.substring(start, pos); } else { @@ -1008,7 +1006,6 @@ export function createScanner( } if (isDigit(ch)) { allowSeparator = true; - isPreviousTokenSeparator = false; pos++; continue; } @@ -1021,7 +1018,7 @@ export function createScanner( } function scanNumber(): SyntaxKind { - let start = pos; + const start = pos; let mainFragment: string; if (charCodeUnchecked(pos) === CharacterCodes._0) { pos++; @@ -1040,9 +1037,6 @@ export function createScanner( else { tokenValue = "" + parseInt(tokenValue, 8); tokenFlags |= TokenFlags.Octal; - const withMinus = token === SyntaxKind.MinusToken; - const literal = (withMinus ? "-" : "") + "0o" + (+tokenValue).toString(8); - if (withMinus) start--; return SyntaxKind.NumericLiteral; } } @@ -1486,14 +1480,12 @@ export function createScanner( function scanBinaryOrOctalDigits(base: 2 | 8): string { let value = ""; let separatorAllowed = false; - let isPreviousTokenSeparator = false; while (true) { const ch = charCodeUnchecked(pos); if (ch === CharacterCodes._) { tokenFlags |= TokenFlags.ContainsSeparator; if (separatorAllowed) { separatorAllowed = false; - isPreviousTokenSeparator = true; } pos++; continue; @@ -1504,7 +1496,6 @@ export function createScanner( } value += text[pos]; pos++; - isPreviousTokenSeparator = false; } return value; } @@ -2143,17 +2134,12 @@ export function createScanner( } else { pos++; - let regExpFlags: number = RegularExpressionFlags.None; while (true) { const ch = codePointChecked(pos); if (ch === CharacterCodes.EOF || !isIdentifierPart(ch)) { break; } const size = charSize(ch); - const flag = characterCodeToRegularExpressionFlag(ch); - if (flag !== undefined) { - regExpFlags |= flag; - } pos += size; } } diff --git a/packages/typescript/src/ast/spanMap.ts b/packages/typescript/src/ast/spanMap.ts index c83e7ba4af02e..4ffe08d5ec43a 100644 --- a/packages/typescript/src/ast/spanMap.ts +++ b/packages/typescript/src/ast/spanMap.ts @@ -53,7 +53,7 @@ export class SpanMap { * and ranges crossing segment boundaries map their endpoints with `Approximate` fidelity. */ virtualToOriginalSpan(range: ReadonlyTextRange): MappedRange { - return this.mapRange(range, this.segments, false); + return this.mapRange(range, this.segments, /*reverse*/ false); } /** Maps a visible LS result only when every covered segment participates in `feature`. */ @@ -64,12 +64,12 @@ export class SpanMap { /** Maps a virtual position to original text, using `None` fidelity for synthesized gaps. */ virtualToOriginalPosition(position: number): MappedPosition { - return this.mapPoint(position, this.segments, false); + return this.mapPoint(position, this.segments, /*reverse*/ false); } virtualToOriginalPositionForFeature(position: number, feature: SpanMapFeature): MappedPosition { const mapped = this.virtualToOriginalPosition(position); - const [index, inside] = segmentIndexAt(this.segments, position, false); + const [index, inside] = segmentIndexAt(this.segments, position, /*reverse*/ false); return inside && supportsFeature(this.segments[index], feature) ? mapped : { ...mapped, fidelity: SpanMapFidelity.None }; } @@ -85,14 +85,15 @@ export class SpanMap { for (const segment of group.segments) { if (!supportsFeature(segment, feature)) continue; const mapped = segment.kind === SpanMapKind.Verbatim - ? { position: mapVerbatimPosition(segment, position, true), fidelity: SpanMapFidelity.Exact } + ? { position: mapVerbatimPosition(segment, position, /*reverse*/ true), fidelity: SpanMapFidelity.Exact } : { position: group.atEnd ? segment.virtualEnd : segment.virtualStart, fidelity: SpanMapFidelity.Atom }; if (!results.some(result => result.position === mapped.position && result.fidelity === mapped.fidelity)) { results.push(mapped); } } } - return results.sort((left, right) => left.position - right.position); + results.sort((left, right) => left.position - right.position); + return results; } /** @@ -134,7 +135,10 @@ export class SpanMap { const containing = startSegments.filter(segment => end <= segment.originalEnd); if (containing.length > 0) { const results = [...originalToVirtualSpansInSegments(containing, start, end, feature)]; - if (results.length > 0) return results.sort((left, right) => left.range.pos - right.range.pos); + if (results.length > 0) { + results.sort((left, right) => left.range.pos - right.range.pos); + return results; + } } const starts = [...originalStartProjections(startSegments, start, feature)].sort((left, right) => left - right); const ends = [...originalEndProjections(endSegments, end, feature)].sort((left, right) => left - right); @@ -173,8 +177,8 @@ export class SpanMap { return { range: { pos: position, end: position }, fidelity: SpanMapFidelity.None }; } - const mappedStart = mapBoundary(segments, start, startIndex, startInside, reverse, false); - const mappedEnd = Math.max(mappedStart, mapBoundary(segments, end, endIndex, endInside, reverse, true)); + const mappedStart = mapBoundary(segments, start, startIndex, startInside, reverse, /*high*/ false); + const mappedEnd = Math.max(mappedStart, mapBoundary(segments, end, endIndex, endInside, reverse, /*high*/ true)); return { range: { pos: mappedStart, end: mappedEnd }, fidelity: SpanMapFidelity.Approximate }; } @@ -214,11 +218,12 @@ export class SpanMap { const start = range.pos; const end = Math.max(range.end, start); if (start === end) { - const [index, inside] = segmentIndexAt(this.segments, start, false); + const [index, inside] = segmentIndexAt(this.segments, start, /*reverse*/ false); return inside && supportsFeature(this.segments[index], feature); } - let [index, inside] = segmentIndexAt(this.segments, start, false); + const [startIndex, inside] = segmentIndexAt(this.segments, start, /*reverse*/ false); if (!inside) return false; + let index = startIndex; let coveredThrough = start; while (index < this.segments.length && coveredThrough < end) { const segment = this.segments[index]; @@ -248,7 +253,7 @@ function originalStartProjections(segments: readonly NormalizedSpanMapSegment[], .filter(segment => supportsFeature(segment, feature)) .map(segment => segment.kind === SpanMapKind.Verbatim - ? mapVerbatimPosition(segment, start, true) + ? mapVerbatimPosition(segment, start, /*reverse*/ true) : segment.virtualStart ); } @@ -272,7 +277,7 @@ function originalEndProjections(segments: readonly NormalizedSpanMapSegment[], e .filter(segment => supportsFeature(segment, feature)) .map(segment => segment.kind === SpanMapKind.Verbatim - ? mapVerbatimPosition(segment, end, true) + ? mapVerbatimPosition(segment, end, /*reverse*/ true) : segment.virtualEnd ); } @@ -283,8 +288,8 @@ function originalToVirtualSpansInSegments(segments: readonly NormalizedSpanMapSe .filter(segment => supportsFeature(segment, feature)) .map(segment => { if (segment.kind === SpanMapKind.Verbatim) { - const mappedStart = mapVerbatimPosition(segment, start, true); - const mappedEnd = Math.max(mappedStart, mapVerbatimPosition(segment, end, true)); + const mappedStart = mapVerbatimPosition(segment, start, /*reverse*/ true); + const mappedEnd = Math.max(mappedStart, mapVerbatimPosition(segment, end, /*reverse*/ true)); return { range: { pos: mappedStart, end: mappedEnd }, fidelity: SpanMapFidelity.Exact }; } return { range: { pos: segment.virtualStart, end: segment.virtualEnd }, fidelity: SpanMapFidelity.Atom }; @@ -304,7 +309,7 @@ function segmentsAtOriginalPosition(index: OriginalIndex, position: number): rea // Query intervals that contain position strictly before their exclusive end. Segments starting exactly at // position are appended separately so zero-length segments are included while maxEnd <= position is pruned. const start = firstOriginalSegmentAtOrAfter(index.segments, position); - const results = segmentsEndingAtOrAfter(index, start, position, false); + const results = segmentsEndingAtOrAfter(index, start, position, /*includeEnd*/ false); const end = firstOriginalSegmentAfter(index.segments, position); results.push(...index.segments.slice(start, end)); return results.length > 0 ? results : undefined; @@ -383,7 +388,7 @@ interface SegmentGroupAtOriginalPosition { */ function segmentGroupsAtOriginalPosition(index: OriginalIndex, position: number): readonly SegmentGroupAtOriginalPosition[] { const limit = firstOriginalSegmentAfter(index.segments, position); - const segments = segmentsEndingAtOrAfter(index, limit, position, true); + const segments = segmentsEndingAtOrAfter(index, limit, position, /*includeEnd*/ true); const groups: SegmentGroupAtOriginalPosition[] = []; for (let start = 0; start < segments.length;) { let end = start + 1; diff --git a/packages/typescript/src/ast/utils.ts b/packages/typescript/src/ast/utils.ts index dfaecc7ae1b5f..54c6c77b235c2 100644 --- a/packages/typescript/src/ast/utils.ts +++ b/packages/typescript/src/ast/utils.ts @@ -18,7 +18,9 @@ import type { Expression, HasExpression, HasInitializer, + Identifier, ModifierLike, + NumericOrStringLikeLiteral, ObjectAssignmentInitializer, PropertyAccessExpression, PropertyAssignment, @@ -29,8 +31,7 @@ import type { Node } from "./ast.ts"; import { isAccessExpression, isIdentifier, - isNumericLiteral, - isStringLiteralLikeNode, + isNumericOrStringLikeLiteral, } from "./is.generated.ts"; import { skipOuterExpressions } from "./is.ts"; import { modifierToFlag } from "./modifiers.ts"; @@ -102,15 +103,15 @@ export function cast(value: TIn | undefined, test: } export function hasExpression(node: Node): node is HasExpression { - return "expression" in node; + return !!(node as HasExpression).expression; } export function hasInitializer(node: Node): node is HasInitializer { - return "initializer" in node; + return !!(node as HasInitializer).initializer; } export function hasObjectAssignmentInitializer(node: Node): node is ObjectAssignmentInitializer { - return "objectAssignmentInitializer" in node; + return !!(node as ObjectAssignmentInitializer).objectAssignmentInitializer; } export function isExternalModule(file: SourceFile): boolean { @@ -129,9 +130,7 @@ function getRootDeclaration(node: Node): Node { } function getModifierFlags(node: Node): ModifierFlags { - const modifiers = "modifiers" in node - ? (node as Node & { readonly modifiers?: readonly ModifierLike[]; }).modifiers - : undefined; + const modifiers = (node as Node & { readonly modifiers?: readonly ModifierLike[]; }).modifiers; let flags = ModifierFlags.None; if (modifiers) { for (const modifier of modifiers) { @@ -161,20 +160,17 @@ function skipParentheses(node: Expression): Expression { return skipOuterExpressions(node, OuterExpressionKinds.Parentheses); } -function isStringOrNumericLiteralLike(node: Node): node is DeclarationName { - return isStringLiteralLikeNode(node) || isNumericLiteral(node); -} - -function getElementOrPropertyAccessName(node: AccessExpression): DeclarationName | undefined { +function getElementOrPropertyAccessName(node: AccessExpression): Identifier | NumericOrStringLikeLiteral | undefined { if (node.kind === SyntaxKind.PropertyAccessExpression) { return isIdentifier(node.name) ? node.name : undefined; } const argument = skipParentheses(node.argumentExpression); - return isStringOrNumericLiteralLike(argument) ? argument : undefined; + return isNumericOrStringLikeLiteral(argument) ? argument : undefined; } -function getNameText(node: DeclarationName | undefined): string | undefined { - return node && "text" in node && typeof node.text === "string" ? node.text : undefined; +function getNameText(node: Identifier | NumericOrStringLikeLiteral | undefined): string | undefined { + const text = node?.text; + return typeof text === "string" ? text : undefined; } function isEntityNameExpression(node: Node, allowJS = false): boolean { @@ -187,22 +183,22 @@ function isEntityNameExpression(node: Node, allowJS = false): boolean { if (node.kind === SyntaxKind.ThisKeyword) return true; if (node.kind !== SyntaxKind.ElementAccessExpression) return false; const access = node as ElementAccessExpression; - return isStringOrNumericLiteralLike(access.argumentExpression) && - isEntityNameExpression(access.expression, true); + return isNumericOrStringLikeLiteral(access.argumentExpression) && + isEntityNameExpression(access.expression, /*allowJS*/ true); } function isBindableStaticAccessExpression(node: Node, excludeThisKeyword: boolean): node is AccessExpression { if (node.kind === SyntaxKind.PropertyAccessExpression) { const access = node as PropertyAccessExpression; return !excludeThisKeyword && access.expression.kind === SyntaxKind.ThisKeyword || - isIdentifier(access.name) && isBindableStaticNameExpression(access.expression, true); + isIdentifier(access.name) && isBindableStaticNameExpression(access.expression, /*excludeThisKeyword*/ true); } if (node.kind !== SyntaxKind.ElementAccessExpression) return false; const access = node as ElementAccessExpression; - return isStringOrNumericLiteralLike(access.argumentExpression) && + return isNumericOrStringLikeLiteral(access.argumentExpression) && (!excludeThisKeyword && access.expression.kind === SyntaxKind.ThisKeyword || isEntityNameExpression(access.expression) || - isBindableStaticAccessExpression(access.expression, true)); + isBindableStaticAccessExpression(access.expression, /*excludeThisKeyword*/ true)); } function isBindableStaticNameExpression(node: Node, excludeThisKeyword: boolean): boolean { @@ -224,8 +220,8 @@ function isBindableObjectDefinePropertyCall(node: CallExpression): boolean { return isIdentifier(access.expression) && access.expression.text === "Object" && access.name.text === "defineProperty" && - isStringOrNumericLiteralLike(node.arguments[1]) && - isBindableStaticNameExpression(node.arguments[0], true); + isNumericOrStringLikeLiteral(node.arguments[1]) && + isBindableStaticNameExpression(node.arguments[0], /*excludeThisKeyword*/ true); } function getAssignmentDeclarationKind(node: BinaryExpression | CallExpression): JSDeclarationKind { @@ -318,7 +314,7 @@ function getAssignedName(node: Node): DeclarationName | undefined { if (left.kind === SyntaxKind.PropertyAccessExpression) return (left as PropertyAccessExpression).name; if (left.kind === SyntaxKind.ElementAccessExpression) { const argument = skipParentheses((left as ElementAccessExpression).argumentExpression); - return isStringOrNumericLiteralLike(argument) ? argument : undefined; + return isNumericOrStringLikeLiteral(argument) ? argument : undefined; } return undefined; } diff --git a/packages/typescript/src/ast/visitor.ts b/packages/typescript/src/ast/visitor.ts index aa7d8dac2471e..ff02521dd6a86 100644 --- a/packages/typescript/src/ast/visitor.ts +++ b/packages/typescript/src/ast/visitor.ts @@ -6,10 +6,7 @@ import { SyntaxKind } from "../../enums/syntaxKind.js"; import type { - JSDocComment, JSDocParameterOrPropertyTag, - JSDocParameterTag, - JSDocPropertyTag, Node, NodeArray, } from "./ast.ts"; diff --git a/packages/typescript/src/vscode/extensionApi.ts b/packages/typescript/src/vscode/extensionApi.ts index 05c729a7d70a2..5d84765ec41ca 100644 --- a/packages/typescript/src/vscode/extensionApi.ts +++ b/packages/typescript/src/vscode/extensionApi.ts @@ -8,6 +8,7 @@ export interface Disposable { } export interface Event { + // eslint-disable-next-line @typescript-eslint/prefer-function-type -- Preserve declaration merging for this exported interface. (listener: (event: T) => unknown, thisArgs?: unknown, disposables?: Disposable[] | undefined): Disposable; } @@ -42,7 +43,9 @@ export type DeepReadonly = unknown extends T ? unknown : T extends object ? { export type LspMiddlewareResult = LspMiddlewareRequests[M]["result"]; -export type LspMiddlewareContext = { readonly params: DeepReadonly; }; +export interface LspMiddlewareContext { + readonly params: DeepReadonly; +} export type LspMiddlewareTransformer = ( result: LspMiddlewareResult, diff --git a/packages/typescript/src/vscode/moduleLoader.ts b/packages/typescript/src/vscode/moduleLoader.ts index e6e57064aa039..ef2c5660dc5a8 100644 --- a/packages/typescript/src/vscode/moduleLoader.ts +++ b/packages/typescript/src/vscode/moduleLoader.ts @@ -10,6 +10,12 @@ export interface TypeScriptModuleLoader { importModule(exportPath: K): Promise; } +function hasPackageName(value: unknown): value is { readonly name: string; } { + return typeof value === "object" && value != undefined + && Object.hasOwn(value, "name") + && typeof (value as { readonly name?: unknown; }).name === "string"; +} + /** * Loads the selected installation's API modules in this process. * Pass the SDK's packageJsonPath through your server's initialization options. @@ -29,7 +35,7 @@ export function createTypeScriptModuleLoader(packageJsonPath: string): TypeScrip const manifestPath = await fs.realpath(packageJsonPath); const manifest: unknown = JSON.parse(await fs.readFile(manifestPath, "utf8")); - if (!manifest || typeof manifest !== "object" || !("name" in manifest) || typeof manifest.name !== "string") { + if (!hasPackageName(manifest)) { throw new Error(`TypeScript API package manifest at '${packageJsonPath}' does not contain a package name.`); } const require = createRequire(manifestPath); diff --git a/packages/typescript/src/wasm/transport.ts b/packages/typescript/src/wasm/transport.ts index 1882dde34e979..9a91df17d3778 100644 --- a/packages/typescript/src/wasm/transport.ts +++ b/packages/typescript/src/wasm/transport.ts @@ -102,7 +102,7 @@ export class WasmTransport { private readonly callbacks = new Map(); private readonly fileSystemCallbacks = new Map(); private fs: FileSystemCallbacks | undefined; - private readonly stack: Frame[] = []; + private stack: Frame[] = []; private started = false; private closed = false; @@ -324,7 +324,8 @@ export class WasmTransport { } private abort(error: Error): void { - const frames = this.stack.splice(0); + const frames = this.stack; + this.stack = []; for (const frame of frames) { if (frame.kind === "request" && !frame.settlement) { frame.settlement = { ok: false, error }; @@ -417,7 +418,7 @@ function getReactorExports(instance: WasmReactorInstance): WasmReactorExports { "response_method_len", ] as const; const missing: string[] = required.filter(name => typeof exports[name] !== "function"); - if (exports.memory == null || typeof exports.memory !== "object" || !("buffer" in exports.memory)) { + if (typeof exports.memory !== "object" || exports.memory == undefined || !exports.memory.buffer) { missing.push("memory"); } if (missing.length > 0) { diff --git a/packages/typescript/src/wasm/wasi.ts b/packages/typescript/src/wasm/wasi.ts index d7bebabe8e2a6..7cbc41a24f81b 100644 --- a/packages/typescript/src/wasm/wasi.ts +++ b/packages/typescript/src/wasm/wasi.ts @@ -3,15 +3,13 @@ import type { WasmReactorInstance } from "./transport.ts"; declare namespace WebAssembly { interface Module {} - type Imports = Record>; + type Imports = Record>; interface Instance { readonly exports: Record; } - const Instance: { - new (module: Module, imports?: Imports): Instance; - }; + const Instance: new (module: Module, imports?: Imports) => Instance; interface Memory { readonly buffer: ArrayBufferLike; @@ -27,7 +25,7 @@ declare namespace WebAssembly { interface StreamingTextDecoder { decode( - input?: ArrayBuffer | ArrayBufferView | null, + input?: Uint8Array, options?: { stream?: boolean | undefined; }, ): string; } @@ -153,8 +151,8 @@ function createWasiHost(options: InstantiateWasmOptions): { let length = 0; for (let i = 0; i < iovsLength; i++) { const iovPointer = iovsPointer + i * 8; - const chunkLength = view.getUint32(iovPointer + 4, true); - text += decoder.decode(new Uint8Array(memory.buffer, view.getUint32(iovPointer, true), chunkLength), { stream: true }); + const chunkLength = view.getUint32(iovPointer + 4, /*littleEndian*/ true); + text += decoder.decode(new Uint8Array(memory.buffer, view.getUint32(iovPointer, /*littleEndian*/ true), chunkLength), { stream: true }); length += chunkLength; } view.setUint32(writtenPointer, length, true); @@ -208,10 +206,10 @@ function createWasiHost(options: InstantiateWasmOptions): { for (let i = 0; i < subscriptionsLength; i++) { const subscription = subscriptionsPointer + i * 48; if (view.getUint8(subscription + 8) !== eventTypeClock) continue; - const clockId = view.getUint32(subscription + 16, true); + const clockId = view.getUint32(subscription + 16, /*littleEndian*/ true); if (clockId !== 0 && clockId !== 1) return errnoInvalidArgument; - const timeout = view.getBigUint64(subscription + 24, true); - const flags = view.getUint16(subscription + 40, true); + const timeout = view.getBigUint64(subscription + 24, /*littleEndian*/ true); + const flags = view.getUint16(subscription + 40, /*littleEndian*/ true); const now = clockId === 0 ? Date.now() : performance.now(); const delay = flags & subscriptionClockAbstime ? Number(timeout) / 1e6 - now @@ -231,7 +229,7 @@ function createWasiHost(options: InstantiateWasmOptions): { } new Uint8Array(memory.buffer, eventsPointer, 32).fill(0); - view.setBigUint64(eventsPointer, view.getBigUint64(selected, true), true); + view.setBigUint64(eventsPointer, view.getBigUint64(selected, /*littleEndian*/ true), true); view.setUint8(eventsPointer + 10, eventTypeClock); view.setUint32(eventsLengthPointer, 1, true); return errnoSuccess; diff --git a/packages/typescript/test/api-comparison.bench.ts b/packages/typescript/test/api-comparison.bench.ts index 5a630080e2dd3..c1843351edaef 100644 --- a/packages/typescript/test/api-comparison.bench.ts +++ b/packages/typescript/test/api-comparison.bench.ts @@ -69,7 +69,8 @@ export async function runBenchmarks(options?: { filter?: string; singleIteration await bench.run(); for (const task of bench.tasks) { - if (task.result && "error" in task.result) throw task.result.error; + const error = (task.result as { error?: unknown; } | undefined)?.error; + if (error) throw error; } console.table(bench.table()); @@ -158,17 +159,17 @@ export async function runBenchmarks(options?: { filter?: string; singleIteration function addExecutorBenchmarks() { for (const rounds of [1, flightCount]) { for (const depth of [0, 1, 4, 16]) { - bench.add(`executor only - ${rounds} flights (${depth ? `all depth ${depth}` : "direct batch"})`, () => run(false), { + bench.add(`executor only - ${rounds} flights (${depth ? `all depth ${depth}` : "direct batch"})`, () => run(/*verify*/ false), { async: false, beforeAll: () => { - run(true); + run(/*verify*/ true); }, }); if (depth && rounds > 1) { - bench.add(`executor only - ${rounds} flights (repeated all depth ${depth})`, () => run(false, true), { + bench.add(`executor only - ${rounds} flights (repeated all depth ${depth})`, () => run(/*verify*/ false, /*repeatedJoins*/ true), { async: false, beforeAll: () => { - run(true, true); + run(/*verify*/ true, /*repeatedJoins*/ true); }, }); } @@ -213,6 +214,7 @@ export async function runBenchmarks(options?: { filter?: string; singleIteration } function addDeferBenchmarks() { + // eslint-disable-next-line require-yield -- This child must never start. const child = (function* () { assert.fail("Lifecycle benchmark must not start the child"); })(); @@ -235,10 +237,10 @@ export async function runBenchmarks(options?: { filter?: string; singleIteration for (const rounds of [1, flightCount]) { for (const mode of ["direct", "batch defer", "yield* defer"] as const) { - bench.add(`executor defer - ${rounds} flights (${mode})`, () => run(false), { + bench.add(`executor defer - ${rounds} flights (${mode})`, () => run(/*verify*/ false), { async: false, beforeAll: () => { - run(true); + run(/*verify*/ true); }, }); @@ -298,10 +300,10 @@ export async function runBenchmarks(options?: { filter?: string; singleIteration const rounds = 100; const generatorsPerRound = generatorCount / rounds; for (const mode of ["direct", "yield* defer"] as const) { - bench.add(`executor long batch - ${generatorCount} generators (${mode})`, () => run(false), { + bench.add(`executor long batch - ${generatorCount} generators (${mode})`, () => run(/*verify*/ false), { async: false, beforeAll: () => { - run(true); + run(/*verify*/ true); }, }); @@ -448,7 +450,7 @@ interface AsyncContext { } function collectIdentifierPositions(fileName: string, count: number): number[] { - const sourceFile = ts.createSourceFile(fileName, readFileSync(fileName, "utf8"), ts.ScriptTarget.Latest, true); + const sourceFile = ts.createSourceFile(fileName, readFileSync(fileName, "utf8"), ts.ScriptTarget.Latest, /*setParentNodes*/ true); const positions: number[] = []; sourceFile.forEachChild(function visit(node) { if (node.kind === ts.SyntaxKind.Identifier) { diff --git a/packages/typescript/test/astPredicates.test.ts b/packages/typescript/test/astPredicates.test.ts index 0f97fae203128..a281bfb4f4e51 100644 --- a/packages/typescript/test/astPredicates.test.ts +++ b/packages/typescript/test/astPredicates.test.ts @@ -14,15 +14,75 @@ function createAPI(): API { }); } +test("node property predicates require a value", () => { + const node = Object.create({ + expression: undefined, + initializer: undefined, + objectAssignmentInitializer: undefined, + }) as ast.Node; + assert.equal(ast.hasExpression(node), false); + assert.equal(ast.hasInitializer(node), false); + assert.equal(ast.hasObjectAssignmentInitializer(node), false); + + const expression = factory.createIdentifier("value"); + assert.ok(ast.hasExpression(factory.createExpressionStatement(expression))); + assert.ok(ast.hasInitializer(factory.createVariableDeclaration(factory.createIdentifier("name"), /*exclamationToken*/ undefined, /*type*/ undefined, expression))); + assert.ok(ast.hasObjectAssignmentInitializer(factory.createShorthandPropertyAssignment( + /*modifiers*/ undefined, + factory.createIdentifier("name"), + /*postfixToken*/ undefined, + /*type*/ undefined, + /*equalsToken*/ undefined, + expression, + ))); +}); + +test("type-only alias use recognizes syntactic abstract modifiers", () => { + const name = factory.createIdentifier("key"); + const computed = factory.createComputedPropertyName(name); + const member = { + kind: ast.SyntaxKind.MethodDeclaration, + modifiers: [factory.createToken(ast.SyntaxKind.AbstractKeyword)], + parent: { kind: ast.SyntaxKind.ClassDeclaration }, + }; + Object.defineProperty(name, "parent", { value: computed }); + Object.defineProperty(computed, "parent", { value: member }); + assert.equal(ast.isValidTypeOnlyAliasUseSite(name), true); + member.modifiers = []; + assert.equal(ast.isValidTypeOnlyAliasUseSite(name), false); +}); + +test("AST predicates read properties independently of proxy membership", () => { + const declaration = factory.createFunctionDeclaration( + [factory.createToken(ast.SyntaxKind.ExportKeyword)], + /*asteriskToken*/ undefined, + /*name*/ undefined, + /*typeParameters*/ undefined, + [], + ); + const proxiedDeclaration = new Proxy(declaration, { has: () => false }); + assert.equal(ast.getCombinedModifierFlags(proxiedDeclaration), ast.ModifierFlags.Export); + + const tag = factory.createIdentifier("Component"); + const parent = new Proxy({ kind: ast.SyntaxKind.JsxOpeningElement, tagName: tag }, { has: () => false }); + Object.defineProperty(tag, "parent", { value: parent }); + assert.equal(ast.isValidTypeOnlyAliasUseSite(tag), false); + + const exportsName = new Proxy(factory.createIdentifier("exports"), { has: () => false }); + const access = factory.createPropertyAccessExpression(factory.createIdentifier("module"), /*questionDotToken*/ undefined, exportsName, ast.NodeFlags.JavaScriptFile); + const assignment = factory.createBinaryExpression(/*modifiers*/ undefined, access, /*type*/ undefined, factory.createToken(ast.SyntaxKind.EqualsToken), factory.createIdentifier("value")); + assert.equal(ast.getNameOfDeclaration(assignment), undefined); +}); + test("isAutoAccessorPropertyDeclaration distinguishes accessor modifiers from accessors", () => { const name = factory.createIdentifier("value"); const property: ast.Node = factory.createPropertyDeclaration([factory.createToken(ast.SyntaxKind.AccessorKeyword)], name); assert.ok(ast.isAutoAccessorPropertyDeclaration(property)); const narrowed: ast.AutoAccessorPropertyDeclaration = property; assert.equal(narrowed.name, name); - assert.equal(ast.isAutoAccessorPropertyDeclaration(factory.createPropertyDeclaration(undefined, name)), false); - assert.equal(ast.isAutoAccessorPropertyDeclaration(factory.createGetAccessorDeclaration(undefined, name, undefined, [])), false); - const ordinary = factory.createPropertyDeclaration(undefined, name); + assert.equal(ast.isAutoAccessorPropertyDeclaration(factory.createPropertyDeclaration(/*modifiers*/ undefined, name)), false); + assert.equal(ast.isAutoAccessorPropertyDeclaration(factory.createGetAccessorDeclaration(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, [])), false); + const ordinary = factory.createPropertyDeclaration(/*modifiers*/ undefined, name); if (!ast.isAutoAccessorPropertyDeclaration(ordinary)) { assert.equal(ordinary.name, name); } @@ -30,11 +90,11 @@ test("isAutoAccessorPropertyDeclaration distinguishes accessor modifiers from ac test("isCallChain recognizes continuations without a question-dot token", () => { const name = factory.createIdentifier("f"); - const call: ast.Node = factory.createCallExpression(name, undefined, undefined, [], ast.NodeFlags.OptionalChain); + const call: ast.Node = factory.createCallExpression(name, /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [], ast.NodeFlags.OptionalChain); assert.ok(ast.isCallChain(call)); const narrowed: ast.CallChain = call; assert.equal(narrowed.questionDotToken, undefined); - const ordinary = factory.createCallExpression(name, undefined, undefined, [], ast.NodeFlags.None); + const ordinary = factory.createCallExpression(name, /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [], ast.NodeFlags.None); if (!ast.isCallChain(ordinary)) { assert.equal(ordinary.arguments.length, 0); } @@ -43,12 +103,12 @@ test("isCallChain recognizes continuations without a question-dot token", () => }); test("isClassElement includes static blocks and index signatures but not interface properties", () => { - const signature: ast.Node = factory.createIndexSignatureDeclaration(undefined, []); + const signature: ast.Node = factory.createIndexSignatureDeclaration(/*modifiers*/ undefined, []); assert.ok(ast.isClassElement(signature)); const narrowed: ast.ClassElement = signature; assert.equal(narrowed, signature); - assert.ok(ast.isClassElement(factory.createClassStaticBlockDeclaration(undefined, factory.createBlock([])))); - assert.equal(ast.isClassElement(factory.createPropertySignatureDeclaration(undefined, factory.createIdentifier("x"))), false); + assert.ok(ast.isClassElement(factory.createClassStaticBlockDeclaration(/*modifiers*/ undefined, factory.createBlock([])))); + assert.equal(ast.isClassElement(factory.createPropertySignatureDeclaration(/*modifiers*/ undefined, factory.createIdentifier("x"))), false); }); test("isConstTypeReference rejects qualified names and even empty type argument lists", () => { @@ -67,7 +127,7 @@ test("isDeclarationStatement does not classify variable statements as declaratio const narrowed: ast.Statement & ast.Declaration = declaration; assert.equal(narrowed, declaration); assert.ok(ast.isDeclarationStatement(factory.createMissingDeclaration())); - assert.equal(ast.isDeclarationStatement(factory.createVariableStatement(undefined, factory.createVariableDeclarationList([], ast.NodeFlags.Const))), false); + assert.equal(ast.isDeclarationStatement(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([], ast.NodeFlags.Const))), false); assert.equal(ast.isDeclarationStatement(factory.createBlock([])), false); }); @@ -94,22 +154,22 @@ test("isDeclarationStatement includes declarations produced by JavaScript JSDoc" test("isElementAccessChain uses the chain flag rather than the question-dot token", () => { const name = factory.createIdentifier("obj"); const index = factory.createStringLiteral("key", ast.TokenFlags.None); - const access: ast.Node = factory.createElementAccessExpression(name, undefined, index, ast.NodeFlags.OptionalChain); + const access: ast.Node = factory.createElementAccessExpression(name, /*questionDotToken*/ undefined, index, ast.NodeFlags.OptionalChain); assert.ok(ast.isElementAccessChain(access)); const narrowed: ast.ElementAccessChain = access; assert.equal(narrowed.argumentExpression, index); - assert.equal(ast.isElementAccessChain(factory.createElementAccessExpression(name, undefined, index, ast.NodeFlags.None)), false); - assert.equal(ast.isElementAccessChain(factory.createPropertyAccessExpression(name, undefined, name, ast.NodeFlags.OptionalChain)), false); + assert.equal(ast.isElementAccessChain(factory.createElementAccessExpression(name, /*questionDotToken*/ undefined, index, ast.NodeFlags.None)), false); + assert.equal(ast.isElementAccessChain(factory.createPropertyAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.OptionalChain)), false); }); test("isEmptyBindingElement recursively distinguishes bindings from empty nested patterns", () => { - const empty = factory.createBindingElement(undefined, undefined, factory.createObjectBindingPattern([])); + const empty = factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createObjectBindingPattern([])); assert.ok(ast.isEmptyBindingElement(empty)); assert.ok(ast.isEmptyBindingElement(factory.createOmittedExpression())); assert.ok(ast.isEmptyBindingElement(factory.createBindingElement())); - const binding = factory.createBindingElement(undefined, undefined, factory.createIdentifier("value")); + const binding = factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createIdentifier("value")); assert.equal(ast.isEmptyBindingElement(binding), false); - assert.equal(ast.isEmptyBindingElement(factory.createBindingElement(undefined, undefined, factory.createArrayBindingPattern([binding]))), false); + assert.equal(ast.isEmptyBindingElement(factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createArrayBindingPattern([binding]))), false); }); test("isEmptyBindingElement recognizes parsed array-binding holes", () => { @@ -129,7 +189,7 @@ test("isEmptyBindingElement recognizes parsed array-binding holes", () => { test("isEmptyBindingPattern accepts nested empty patterns but not identifiers", () => { const nested: ast.BindingName = factory.createArrayBindingPattern([ - factory.createBindingElement(undefined, undefined, factory.createObjectBindingPattern([])), + factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createObjectBindingPattern([])), ]); assert.ok(ast.isEmptyBindingPattern(nested)); const narrowed: ast.EmptyBindingPattern = nested; @@ -137,12 +197,12 @@ test("isEmptyBindingPattern accepts nested empty patterns but not identifiers", assert.equal(ast.isEmptyBindingPattern(factory.createIdentifier("value")), false); assert.equal( ast.isEmptyBindingPattern(factory.createObjectBindingPattern([ - factory.createBindingElement(undefined, undefined, factory.createIdentifier("value")), + factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createIdentifier("value")), ])), false, ); const nonempty = factory.createObjectBindingPattern([ - factory.createBindingElement(undefined, undefined, factory.createIdentifier("value")), + factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, factory.createIdentifier("value")), ]); if (!ast.isEmptyBindingPattern(nonempty)) { assert.equal(nonempty.elements.length, 1); @@ -160,46 +220,46 @@ test("isEmptyBindingPattern accepts parsed hole-only and nested empty patterns", }); test("isFunctionLike includes signatures and JSDoc callbacks, not only functions with bodies", () => { - const signature: ast.Node | undefined = factory.createCallSignatureDeclaration(undefined, []); + const signature: ast.Node | undefined = factory.createCallSignatureDeclaration(/*typeParameters*/ undefined, []); assert.ok(ast.isFunctionLike(signature)); const narrowed: ast.SignatureDeclaration | ast.JSDocSignature = signature; assert.equal(narrowed.parameters.length, 0); - assert.ok(ast.isFunctionLike(factory.createJSDocSignature(undefined, []))); - assert.ok(ast.isFunctionLike(factory.createFunctionTypeNode(undefined, [], factory.createKeywordTypeNode(ast.SyntaxKind.VoidKeyword)))); - assert.equal(ast.isFunctionLike(undefined), false); - assert.equal(ast.isFunctionLike(factory.createClassStaticBlockDeclaration(undefined, factory.createBlock([]))), false); + assert.ok(ast.isFunctionLike(factory.createJSDocSignature(/*typeParameters*/ undefined, []))); + assert.ok(ast.isFunctionLike(factory.createFunctionTypeNode(/*typeParameters*/ undefined, [], factory.createKeywordTypeNode(ast.SyntaxKind.VoidKeyword)))); + assert.equal(ast.isFunctionLike(/*node*/ undefined), false); + assert.equal(ast.isFunctionLike(factory.createClassStaticBlockDeclaration(/*modifiers*/ undefined, factory.createBlock([]))), false); }); test("isFunctionOrConstructorTypeNode excludes callable declaration signatures", () => { const result = factory.createKeywordTypeNode(ast.SyntaxKind.VoidKeyword); - const type: ast.Node = factory.createFunctionTypeNode(undefined, [], result); + const type: ast.Node = factory.createFunctionTypeNode(/*typeParameters*/ undefined, [], result); assert.ok(ast.isFunctionOrConstructorTypeNode(type)); const narrowed: ast.FunctionTypeNode | ast.ConstructorTypeNode = type; assert.equal(narrowed.type, result); - assert.ok(ast.isFunctionOrConstructorTypeNode(factory.createConstructorTypeNode(undefined, undefined, [], result))); - assert.equal(ast.isFunctionOrConstructorTypeNode(factory.createCallSignatureDeclaration(undefined, [])), false); + assert.ok(ast.isFunctionOrConstructorTypeNode(factory.createConstructorTypeNode(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], result))); + assert.equal(ast.isFunctionOrConstructorTypeNode(factory.createCallSignatureDeclaration(/*typeParameters*/ undefined, [])), false); }); test("isImportOrExportSpecifier distinguishes named specifiers from namespace imports", () => { const name = factory.createIdentifier("value"); - const specifier: ast.Node = factory.createImportSpecifier(true, undefined, name); + const specifier: ast.Node = factory.createImportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name); assert.ok(ast.isImportOrExportSpecifier(specifier)); const narrowed: ast.ImportSpecifier | ast.ExportSpecifier = specifier; assert.equal(narrowed.isTypeOnly, true); - assert.ok(ast.isImportOrExportSpecifier(factory.createExportSpecifier(false, undefined, name))); + assert.ok(ast.isImportOrExportSpecifier(factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, name))); assert.equal(ast.isImportOrExportSpecifier(factory.createNamespaceImport(name)), false); }); test("isIterationStatement follows labels only when requested", () => { const empty = factory.createEmptyStatement(); const loop: ast.Node = factory.createWhileStatement(factory.createIdentifier("condition"), empty); - assert.ok(ast.isIterationStatement(loop, false)); + assert.ok(ast.isIterationStatement(loop, /*lookInLabeledStatements*/ false)); const narrowed: ast.DoStatement | ast.WhileStatement | ast.ForStatement | ast.ForInStatement | ast.ForOfStatement = loop; assert.equal(narrowed.statement, empty); const labeled = factory.createLabeledStatement(factory.createIdentifier("outer"), factory.createLabeledStatement(factory.createIdentifier("inner"), loop)); - assert.equal(ast.isIterationStatement(labeled, false), false); - assert.equal(ast.isIterationStatement(labeled, true), true); - assert.equal(ast.isIterationStatement(factory.createLabeledStatement(factory.createIdentifier("label"), empty), true), false); + assert.equal(ast.isIterationStatement(labeled, /*lookInLabeledStatements*/ false), false); + assert.equal(ast.isIterationStatement(labeled, /*lookInLabeledStatements*/ true), true); + assert.equal(ast.isIterationStatement(factory.createLabeledStatement(factory.createIdentifier("label"), empty), /*lookInLabeledStatements*/ true), false); }); test("isJsxCallLike includes opening fragments but excludes complete fragments", () => { @@ -207,7 +267,7 @@ test("isJsxCallLike includes opening fragments but excludes complete fragments", assert.ok(ast.isJsxCallLike(opening)); const narrowed: ast.JsxOpeningElement | ast.JsxSelfClosingElement | ast.JsxOpeningFragment = opening; assert.equal(narrowed, opening); - assert.ok(ast.isJsxCallLike(factory.createJsxSelfClosingElement(factory.createIdentifier("Component"), undefined, factory.createJsxAttributes([])))); + assert.ok(ast.isJsxCallLike(factory.createJsxSelfClosingElement(factory.createIdentifier("Component"), /*typeArguments*/ undefined, factory.createJsxAttributes([])))); assert.equal(ast.isJsxCallLike(factory.createJsxFragment(factory.createJsxOpeningFragment(), [], factory.createJsxClosingFragment())), false); }); @@ -218,15 +278,15 @@ test("isNonNullChain distinguishes optional-chain assertions from ordinary asser const narrowed: ast.NonNullChain = assertion; assert.equal(narrowed.expression, name); assert.equal(ast.isNonNullChain(factory.createNonNullExpression(name, ast.NodeFlags.None)), false); - assert.equal(ast.isNonNullChain(factory.createCallExpression(name, undefined, undefined, [], ast.NodeFlags.OptionalChain)), false); + assert.equal(ast.isNonNullChain(factory.createCallExpression(name, /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [], ast.NodeFlags.OptionalChain)), false); }); test("isNullishCoalesce distinguishes nullish coalescing from logical OR", () => { const name = factory.createIdentifier("value"); - const expression = factory.createBinaryExpression(undefined, name, undefined, factory.createToken(ast.SyntaxKind.QuestionQuestionToken), name); + const expression = factory.createBinaryExpression(/*modifiers*/ undefined, name, /*type*/ undefined, factory.createToken(ast.SyntaxKind.QuestionQuestionToken), name); assert.ok(ast.isNullishCoalesce(expression)); assert.equal(expression.left, name); - assert.equal(ast.isNullishCoalesce(factory.createBinaryExpression(undefined, name, undefined, factory.createToken(ast.SyntaxKind.BarBarToken), name)), false); + assert.equal(ast.isNullishCoalesce(factory.createBinaryExpression(/*modifiers*/ undefined, name, /*type*/ undefined, factory.createToken(ast.SyntaxKind.BarBarToken), name)), false); assert.equal(ast.isNullishCoalesce(name), false); }); @@ -238,7 +298,7 @@ test("isObjectLiteralElement includes JSX attributes as well as object spreads", assert.equal(narrowed, attribute); assert.ok(ast.isObjectLiteralElement(factory.createJsxSpreadAttribute(name))); assert.ok(ast.isObjectLiteralElement(factory.createSpreadAssignment(name))); - assert.equal(ast.isObjectLiteralElement(factory.createPropertyDeclaration(undefined, name)), false); + assert.equal(ast.isObjectLiteralElement(factory.createPropertyDeclaration(/*modifiers*/ undefined, name)), false); }); test("isOptionalChain includes non-null continuations but rejects flagged unrelated nodes", () => { @@ -247,7 +307,7 @@ test("isOptionalChain includes non-null continuations but rejects flagged unrela assert.ok(ast.isOptionalChain(chain)); const narrowed: ast.OptionalChain = chain; assert.equal(narrowed.expression, name); - assert.ok(ast.isOptionalChain(factory.createCallExpression(name, undefined, undefined, [], ast.NodeFlags.OptionalChain))); + assert.ok(ast.isOptionalChain(factory.createCallExpression(name, /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [], ast.NodeFlags.OptionalChain))); assert.equal(ast.isOptionalChain(factory.createNonNullExpression(name, ast.NodeFlags.None)), false); const unrelated = factory.createParenthesizedExpression(name); Object.defineProperty(unrelated, "flags", { value: ast.NodeFlags.OptionalChain }); @@ -256,24 +316,24 @@ test("isOptionalChain includes non-null continuations but rejects flagged unrela test("isParameterPropertyDeclaration requires both a property modifier and a constructor", () => { const name = factory.createIdentifier("value"); - const constructor = factory.createConstructorDeclaration(undefined, undefined, []); - const parameter: ast.Node = factory.createParameterDeclaration([factory.createToken(ast.SyntaxKind.ReadonlyKeyword)], undefined, name); + const constructor = factory.createConstructorDeclaration(/*modifiers*/ undefined, /*typeParameters*/ undefined, []); + const parameter: ast.Node = factory.createParameterDeclaration([factory.createToken(ast.SyntaxKind.ReadonlyKeyword)], /*dotDotDotToken*/ undefined, name); assert.ok(ast.isParameterPropertyDeclaration(parameter, constructor)); const narrowed: ast.ParameterPropertyDeclaration = parameter; assert.equal(narrowed.name, name); - assert.equal(ast.isParameterPropertyDeclaration(parameter, factory.createFunctionDeclaration(undefined, undefined, undefined, undefined, [])), false); - assert.equal(ast.isParameterPropertyDeclaration(factory.createParameterDeclaration(undefined, undefined, name), constructor), false); - assert.equal(ast.isParameterPropertyDeclaration(factory.createPropertyDeclaration(undefined, name), constructor), false); + assert.equal(ast.isParameterPropertyDeclaration(parameter, factory.createFunctionDeclaration(/*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [])), false); + assert.equal(ast.isParameterPropertyDeclaration(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name), constructor), false); + assert.equal(ast.isParameterPropertyDeclaration(factory.createPropertyDeclaration(/*modifiers*/ undefined, name), constructor), false); }); test("isPropertyAccessChain includes chain continuations without their own question-dot token", () => { const name = factory.createIdentifier("value"); - const access: ast.Node = factory.createPropertyAccessExpression(name, undefined, name, ast.NodeFlags.OptionalChain); + const access: ast.Node = factory.createPropertyAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.OptionalChain); assert.ok(ast.isPropertyAccessChain(access)); const narrowed: ast.PropertyAccessChain = access; assert.equal(narrowed.name, name); - assert.equal(ast.isPropertyAccessChain(factory.createPropertyAccessExpression(name, undefined, name, ast.NodeFlags.None)), false); - assert.equal(ast.isPropertyAccessChain(factory.createElementAccessExpression(name, undefined, name, ast.NodeFlags.OptionalChain)), false); + assert.equal(ast.isPropertyAccessChain(factory.createPropertyAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.None)), false); + assert.equal(ast.isPropertyAccessChain(factory.createElementAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.OptionalChain)), false); }); test("isPropertyAccessOrQualifiedName accepts entity names and expressions, not element access", () => { @@ -282,19 +342,19 @@ test("isPropertyAccessOrQualifiedName accepts entity names and expressions, not assert.ok(ast.isPropertyAccessOrQualifiedName(qualified)); const narrowed: ast.PropertyAccessExpression | ast.QualifiedName = qualified; assert.equal(narrowed, qualified); - assert.ok(ast.isPropertyAccessOrQualifiedName(factory.createPropertyAccessExpression(name, undefined, name, ast.NodeFlags.None))); - assert.equal(ast.isPropertyAccessOrQualifiedName(factory.createElementAccessExpression(name, undefined, name, ast.NodeFlags.None)), false); + assert.ok(ast.isPropertyAccessOrQualifiedName(factory.createPropertyAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.None))); + assert.equal(ast.isPropertyAccessOrQualifiedName(factory.createElementAccessExpression(name, /*questionDotToken*/ undefined, name, ast.NodeFlags.None)), false); }); test("isRestParameter supports syntactic rest parameters and JSDoc variadic types", () => { const name = factory.createIdentifier("values"); const type = factory.createJSDocVariadicType(factory.createKeywordTypeNode(ast.SyntaxKind.StringKeyword)); - assert.ok(ast.isRestParameter(factory.createParameterDeclaration(undefined, factory.createToken(ast.SyntaxKind.DotDotDotToken), name))); - assert.ok(ast.isRestParameter(factory.createParameterDeclaration(undefined, undefined, name, undefined, type))); - assert.ok(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, false, type, false, undefined))); - assert.ok(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, false, factory.createJSDocTypeExpression(type), false, undefined))); - assert.equal(ast.isRestParameter(factory.createParameterDeclaration(undefined, undefined, name)), false); - assert.equal(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, false, undefined, false, undefined)), false); + assert.ok(ast.isRestParameter(factory.createParameterDeclaration(/*modifiers*/ undefined, factory.createToken(ast.SyntaxKind.DotDotDotToken), name))); + assert.ok(ast.isRestParameter(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, type))); + assert.ok(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, /*isBracketed*/ false, type, /*isNameFirst*/ false, /*comment*/ undefined))); + assert.ok(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, /*isBracketed*/ false, factory.createJSDocTypeExpression(type), /*isNameFirst*/ false, /*comment*/ undefined))); + assert.equal(ast.isRestParameter(factory.createParameterDeclaration(/*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)), false); + assert.equal(ast.isRestParameter(factory.createJSDocParameterTag(factory.createIdentifier("param"), name, /*isBracketed*/ false, /*typeExpression*/ undefined, /*isNameFirst*/ false, /*comment*/ undefined)), false); }); test("isStringLiteralOrJsxExpression excludes template literals and full JSX elements", () => { @@ -321,29 +381,29 @@ test("isStringTextContainingNode includes template fragments but not template ex test("isTypeElement includes accessors and synthetic elisions but excludes method declarations", () => { const name = factory.createIdentifier("value"); - const accessor: ast.Node = factory.createGetAccessorDeclaration(undefined, name, undefined, []); + const accessor: ast.Node = factory.createGetAccessorDeclaration(/*modifiers*/ undefined, name, /*typeParameters*/ undefined, []); assert.ok(ast.isTypeElement(accessor)); const narrowed: ast.TypeElement = accessor; assert.equal(narrowed, accessor); assert.ok(ast.isTypeElement(factory.createNotEmittedTypeElement())); - assert.ok(ast.isTypeElement(factory.createCallSignatureDeclaration(undefined, []))); - assert.equal(ast.isTypeElement(factory.createMethodDeclaration(undefined, undefined, name, undefined, undefined, [])), false); + assert.ok(ast.isTypeElement(factory.createCallSignatureDeclaration(/*typeParameters*/ undefined, []))); + assert.equal(ast.isTypeElement(factory.createMethodDeclaration(/*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*postfixToken*/ undefined, /*typeParameters*/ undefined, [])), false); }); test("isClassOrTypeElement unifies class-only and type-only members", () => { - const member: ast.Node = factory.createClassStaticBlockDeclaration(undefined, factory.createBlock([])); + const member: ast.Node = factory.createClassStaticBlockDeclaration(/*modifiers*/ undefined, factory.createBlock([])); assert.ok(ast.isClassOrTypeElement(member)); const narrowed: ast.ClassElement | ast.TypeElement = member; assert.equal(narrowed, member); - assert.ok(ast.isClassOrTypeElement(factory.createCallSignatureDeclaration(undefined, []))); - assert.equal(ast.isClassOrTypeElement(factory.createPropertyAssignment(undefined, factory.createIdentifier("value"), undefined, undefined, factory.createNumericLiteral("1", ast.TokenFlags.None))), false); + assert.ok(ast.isClassOrTypeElement(factory.createCallSignatureDeclaration(/*typeParameters*/ undefined, []))); + assert.equal(ast.isClassOrTypeElement(factory.createPropertyAssignment(/*modifiers*/ undefined, factory.createIdentifier("value"), /*postfixToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral("1", ast.TokenFlags.None))), false); }); test("isTypeOnlyImportDeclaration inherits type-only status but not defer status", () => { const name = factory.createIdentifier("value"); - const specifier = factory.createImportSpecifier(false, undefined, name); + const specifier = factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, name); const bindings = factory.createNamedImports([specifier]); - const clause = factory.createImportClause(ast.SyntaxKind.TypeKeyword, undefined, bindings); + const clause = factory.createImportClause(ast.SyntaxKind.TypeKeyword, /*name*/ undefined, bindings); Object.defineProperty(specifier, "parent", { value: bindings }); Object.defineProperty(bindings, "parent", { value: clause }); const node: ast.Node = specifier; @@ -351,26 +411,26 @@ test("isTypeOnlyImportDeclaration inherits type-only status but not defer status const narrowed: ast.TypeOnlyImportDeclaration = node; assert.equal(narrowed, specifier); assert.ok(ast.isTypeOnlyImportDeclaration(clause)); - assert.ok(ast.isTypeOnlyImportDeclaration(factory.createImportSpecifier(true, undefined, name))); + assert.ok(ast.isTypeOnlyImportDeclaration(factory.createImportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name))); assert.equal(ast.isTypeOnlyImportDeclaration(factory.createImportClause(ast.SyntaxKind.DeferKeyword, name)), false); assert.equal(ast.isTypeOnlyImportDeclaration(factory.createIdentifier("value")), false); - const valueSpecifier = factory.createImportSpecifier(false, undefined, name); + const valueSpecifier = factory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, name); assert.equal(ast.isTypeOnlyImportDeclaration(valueSpecifier), false); if (!ast.isTypeOnlyImportDeclaration(valueSpecifier)) { assert.equal(valueSpecifier.name, name); } const namespace = factory.createNamespaceImport(name); - Object.defineProperty(namespace, "parent", { value: factory.createImportClause(ast.SyntaxKind.TypeKeyword, undefined, namespace) }); + Object.defineProperty(namespace, "parent", { value: factory.createImportClause(ast.SyntaxKind.TypeKeyword, /*name*/ undefined, namespace) }); assert.ok(ast.isTypeOnlyImportDeclaration(namespace)); - assert.ok(ast.isTypeOnlyImportDeclaration(factory.createImportEqualsDeclaration(undefined, true, name, name))); - assert.equal(ast.isTypeOnlyImportDeclaration(factory.createImportEqualsDeclaration(undefined, false, name, name)), false); + assert.ok(ast.isTypeOnlyImportDeclaration(factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ true, name, name))); + assert.equal(ast.isTypeOnlyImportDeclaration(factory.createImportEqualsDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, name, name)), false); }); test("isTypeOnlyExportDeclaration distinguishes export-star from named export containers", () => { const name = factory.createIdentifier("value"); - const specifier = factory.createExportSpecifier(false, undefined, name); + const specifier = factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, name); const bindings = factory.createNamedExports([specifier]); - const declaration = factory.createExportDeclaration(undefined, true, bindings); + const declaration = factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ true, bindings); Object.defineProperty(specifier, "parent", { value: bindings }); Object.defineProperty(bindings, "parent", { value: declaration }); const node: ast.Node = specifier; @@ -378,32 +438,32 @@ test("isTypeOnlyExportDeclaration distinguishes export-star from named export co const narrowed: ast.TypeOnlyExportDeclaration = node; assert.equal(narrowed, specifier); assert.equal(ast.isTypeOnlyExportDeclaration(declaration), false); - assert.ok(ast.isTypeOnlyExportDeclaration(factory.createExportDeclaration(undefined, true, undefined, factory.createStringLiteral("module", ast.TokenFlags.None)))); - assert.equal(ast.isTypeOnlyExportDeclaration(factory.createExportDeclaration(undefined, false, undefined, factory.createStringLiteral("module", ast.TokenFlags.None))), false); - assert.ok(ast.isTypeOnlyExportDeclaration(factory.createExportSpecifier(true, undefined, name))); - const valueSpecifier = factory.createExportSpecifier(false, undefined, name); + assert.ok(ast.isTypeOnlyExportDeclaration(factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ true, /*exportClause*/ undefined, factory.createStringLiteral("module", ast.TokenFlags.None)))); + assert.equal(ast.isTypeOnlyExportDeclaration(factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, factory.createStringLiteral("module", ast.TokenFlags.None))), false); + assert.ok(ast.isTypeOnlyExportDeclaration(factory.createExportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name))); + const valueSpecifier = factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, name); assert.equal(ast.isTypeOnlyExportDeclaration(valueSpecifier), false); if (!ast.isTypeOnlyExportDeclaration(valueSpecifier)) { assert.equal(valueSpecifier.name, name); } const namespace = factory.createNamespaceExport(name); - Object.defineProperty(namespace, "parent", { value: factory.createExportDeclaration(undefined, true, namespace) }); + Object.defineProperty(namespace, "parent", { value: factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ true, namespace) }); assert.ok(ast.isTypeOnlyExportDeclaration(namespace)); }); test("isTypeOnlyImportOrExportDeclaration includes both kinds of explicit type-only aliases", () => { const name = factory.createIdentifier("value"); - const node: ast.Node = factory.createImportSpecifier(true, undefined, name); + const node: ast.Node = factory.createImportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name); assert.ok(ast.isTypeOnlyImportOrExportDeclaration(node)); const narrowed: ast.TypeOnlyAliasDeclaration = node; assert.equal(narrowed, node); - assert.ok(ast.isTypeOnlyImportOrExportDeclaration(factory.createExportSpecifier(true, undefined, name))); - assert.equal(ast.isTypeOnlyImportOrExportDeclaration(factory.createImportClause(undefined, name)), false); + assert.ok(ast.isTypeOnlyImportOrExportDeclaration(factory.createExportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name))); + assert.equal(ast.isTypeOnlyImportOrExportDeclaration(factory.createImportClause(/*phaseModifier*/ undefined, name)), false); }); test("isPartOfTypeOnlyImportOrExportDeclaration includes the alias itself and its descendants", () => { const name = factory.createIdentifier("value"); - const specifier = factory.createImportSpecifier(true, undefined, name); + const specifier = factory.createImportSpecifier(/*isTypeOnly*/ true, /*propertyName*/ undefined, name); Object.defineProperty(name, "parent", { value: specifier }); assert.ok(ast.isPartOfTypeOnlyImportOrExportDeclaration(name)); assert.ok(ast.isPartOfTypeOnlyImportOrExportDeclaration(specifier)); diff --git a/packages/typescript/test/async/api.test.ts b/packages/typescript/test/async/api.test.ts index 582672974ff4f..cface4f37fefd 100644 --- a/packages/typescript/test/async/api.test.ts +++ b/packages/typescript/test/async/api.test.ts @@ -48,7 +48,6 @@ import { type PathKey, type PropertyAccessExpression, type RootedFilePath, - type SourceFile, SyntaxKind, TokenFlags, tryGetAmbientModuleNameFromSymbolName, @@ -402,7 +401,7 @@ function g(before = 1, required: number, after = 2, ...rest: number[]) {} describe("API", { concurrency }, () => { test("getCurrentLanguageServerSnapshot is LSP-only", async () => { - if (!!false) { + async function _checkTypes() { await using standalone = new API(); // @ts-expect-error The standalone API has no canonical language server state. void standalone.getCurrentLanguageServerSnapshot(); @@ -418,7 +417,7 @@ describe("API", { concurrency }, () => { }], }); const baseSnapshot = undefined! as Snapshot; - void lsp.getCurrentLanguageServerSnapshot(undefined, baseSnapshot); + void lsp.getCurrentLanguageServerSnapshot(/*args*/ undefined, baseSnapshot); void standalone.createSnapshot({ createPrograms: [{ rootFiles: [], compilerOptions: {}, options: { projectReferences: [{ path: "/tsconfig.json" }] } }] }); void standalone.createModuleResolver({ outDir: "dist", rootDirs: ["src"], typeRoots: ["types"] }); @@ -440,7 +439,7 @@ describe("API", { concurrency }, () => { // @ts-expect-error Snapshot update parameters are excess-property checked. void baseSnapshot.update({ fileChanges: { changed: ["/index.ts"] } }); // @ts-expect-error Snapshot updates require an explicit changes object. - void baseSnapshot.update(undefined); + void baseSnapshot.update(/*params*/ undefined); // @ts-expect-error Language server snapshot parameters are excess-property checked. void lsp.getCurrentLanguageServerSnapshot({ fileChanges: { changed: ["/index.ts"] } }); @@ -661,7 +660,7 @@ describe("API", { concurrency }, () => { ); assert.deepEqual(config.fileNames, ["/src/index.ts"]); assert.equal(config.options.strict, true); - assert.equal("configFilePath" in config.options, false); + assert.equal(Reflect.has(config.options, "configFilePath"), false); assert.equal(config.compileOnSave, false); assert.deepEqual(config.errors, []); }); @@ -669,7 +668,8 @@ describe("API", { concurrency }, () => { test("parseJsonConfigFileContent accepts non-object JSON", async () => { await using api = spawnAPI(); - const config = await api.parseJsonConfigFileContent(null, { configDirectory: "/src" }); + // eslint-disable-next-line no-restricted-syntax -- Exercise a null JSON configuration. + const config = await api.parseJsonConfigFileContent(/*json*/ null, { configDirectory: "/src" }); assert.deepEqual([...config.fileNames].sort(), ["/src/foo.ts", "/src/index.ts"]); assert.deepEqual(config.errors, []); }); @@ -719,6 +719,7 @@ describe("API", { concurrency }, () => { await using api = spawnAPI(); const config = await api.parseJsonConfigFileContent( + // eslint-disable-next-line no-restricted-syntax -- Exercise invalid null JSON array elements. { files: [null], include: [null], exclude: [null] }, { configDirectory: "/src" }, ); @@ -836,7 +837,7 @@ describe("API", { concurrency }, () => { test("getSymbol rejects synthesized declarations", async () => { await using api = spawnAPI(); - const local = createVariableDeclaration(createIdentifier("local"), undefined, undefined, undefined); + const local = createVariableDeclaration(createIdentifier("local"), /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); await assert.rejects(getSymbol(local), /Source file not found/); // @sync: assert.throws(() => getSymbol(local), /Source file not found/); await assert.rejects(api.getSymbol(local), /Source file not found/); // @sync: assert.throws(() => api.getSymbol(local), /Source file not found/); @@ -847,7 +848,7 @@ describe("API", { concurrency }, () => { const deepClone = getSynthesizedDeepClone(declaration); await assert.rejects(getSymbol(shallowClone), /Source file not found/); // @sync: assert.throws(() => getSymbol(shallowClone), /Source file not found/); await assert.rejects(api.getSymbol(deepClone), /Source file not found/); // @sync: assert.throws(() => api.getSymbol(deepClone), /Source file not found/); - assert.equal("getSymbol" in declaration, false); + assert.equal(Reflect.has(declaration, "getSymbol"), false); }); test("source files own separate declaration result and request caches", async () => { @@ -991,13 +992,13 @@ describe("API", { concurrency }, () => { const parsed = parseNodeHandleFromCompiler(getNodeId(declaration)); assert.equal(getNodeRequestHandle(declaration), `${parsed.index}.#${parsed.sourceFileId}`); - fs.writeFile!(toRootedFilePath("/other.ts", undefined), "export const other = 2;"); + fs.writeFile(toRootedFilePath("/other.ts", /*currentDirectory*/ undefined), "export const other = 2;"); const unchanged = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/other.ts"] } }); const unchangedProject = unchanged.getConfiguredProject("/tsconfig.json")!; assert.ok(await unchangedProject.checker.getTypeAtLocation(declaration)); assert.strictEqual(await handle.resolve(unchangedProject), declaration); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export function f() { return 'changed'; }"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export function f() { return 'changed'; }"); const changed = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/index.ts"] } }); const changedProject = changed.getConfiguredProject("/tsconfig.json")!; await assert.rejects(changedProject.checker.getTypeAtLocation(declaration), /could not be resolved/); // @sync: assert.throws(() => changedProject.checker.getTypeAtLocation(declaration), /could not be resolved/); @@ -1067,8 +1068,8 @@ describe("API", { concurrency }, () => { }); assert.equal(snapshot.getProjects().length, 2); assert.deepEqual(snapshot.getProjects().map(project => project.parsedCommandLine.fileNames), [["/src/a.ts"], ["/src/b.ts"]]); - assert.equal(snapshot.operation.createdPrograms!.length, 2); - for (const program of snapshot.operation.createdPrograms!) { + assert.equal(snapshot.operation.createdPrograms.length, 2); + for (const program of snapshot.operation.createdPrograms) { const syntheticProjectId: SyntheticProjectId = program.id; void syntheticProjectId; assert.strictEqual(snapshot.getProgram(program.id), program); @@ -1093,7 +1094,8 @@ describe("API", { concurrency }, () => { if ( method === "release" && typeof params === "object" - && params !== null + && params != undefined + // eslint-disable-next-line local/no-in-operator -- Narrow the request parameters. && "snapshot" in params && params.snapshot === snapshot.id && duplicateReference @@ -1102,7 +1104,8 @@ describe("API", { concurrency }, () => { return true; } const response = await apiRequest(method, params); - if (method !== "updateSnapshot" || typeof response !== "object" || response === null) return response; + if (method !== "updateSnapshot" || typeof response !== "object" || response == undefined) return response; + // eslint-disable-next-line local/no-in-operator -- Narrow the response. if (!("snapshot" in response) || typeof response.snapshot !== "number") return response; await apiRequest("release", { snapshot: response.snapshot }); duplicateReference = true; @@ -1143,9 +1146,9 @@ describe("API", { concurrency }, () => { }); test("snapshot.update reconfigures module resolution providers", async () => { - const root = toRootedFilePath("/src/index.ts", undefined); - const providedA = toRootedFilePath("/a.d.ts", undefined); - const providedB = toRootedFilePath("/b.d.ts", undefined); + const root = toRootedFilePath("/src/index.ts", /*currentDirectory*/ undefined); + const providedA = toRootedFilePath("/a.d.ts", /*currentDirectory*/ undefined); + const providedB = toRootedFilePath("/b.d.ts", /*currentDirectory*/ undefined); const { api: disposableAPI, fs } = spawnAPIWithFS({ [root]: `import { value } from "pkg"; export { value };`, [providedA]: `export declare const value: "a";`, @@ -1173,10 +1176,10 @@ describe("API", { concurrency }, () => { }); const initial = await api.createSnapshot({ createPrograms: [createProgram(resolverA)] }); - const programId = initial.operation.createdPrograms![0].id; + const programId = initial.operation.createdPrograms[0].id; assert.deepEqual([...await initial.getProgram(programId)!.getSourceFileNames()].sort(), [providedA, root]); assert.equal( - (await resolverA.resolveModuleName("pkg", "/src", undefined, { snapshot: initial })).resolvedModule?.resolvedFileName, + (await resolverA.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: initial })).resolvedModule?.resolvedFileName, providedA, ); assert.equal((await resolverA.resolveModuleName("pkg", "/src")).resolvedModule?.resolvedFileName, providedA); @@ -1186,7 +1189,7 @@ describe("API", { concurrency }, () => { }); assert.deepEqual([...await sameSet.getProgram(programId)!.getSourceFileNames()].sort(), [providedA, root]); - fs.writeFile!(root, `import { value } from "pkg"; export const updated = value;`); + fs.writeFile(root, `import { value } from "pkg"; export const updated = value;`); const sameSetAfterEdit = await sameSet.update({ reconfigurePrograms: [{ id: programId, ...createProgram(resolverA) }], fileNotifications: { changed: [root] }, @@ -1199,7 +1202,7 @@ describe("API", { concurrency }, () => { assert.deepEqual([...await changedSet.getProgram(programId)!.getSourceFileNames()].sort(), [providedB, root]); const removedSet = await sameSetAfterEdit.update({ - reconfigurePrograms: [{ id: programId, ...createProgram(undefined) }], + reconfigurePrograms: [{ id: programId, ...createProgram(/*moduleResolver*/ undefined) }], }); assert.deepEqual(await removedSet.getProgram(programId)!.getSourceFileNames(), [root]); @@ -1221,7 +1224,7 @@ describe("API", { concurrency }, () => { const callbackSnapshot = await api.createSnapshot({ createPrograms: [createProgram(callbackResolver)], }); - const callbackProgramId = callbackSnapshot.operation.createdPrograms![0].id; + const callbackProgramId = callbackSnapshot.operation.createdPrograms[0].id; const repeatedCallback = await callbackSnapshot.update({ reconfigurePrograms: [{ id: callbackProgramId, ...createProgram(callbackResolver) }], }); @@ -1238,13 +1241,13 @@ describe("API", { concurrency }, () => { tsBuildInfoFile: "cache/build.tsbuildinfo", typeRoots: ["types"], }); - const result = await resolver.resolveModuleName("./missing", "/src", undefined); + const result = await resolver.resolveModuleName("./missing", "/src", /*resolutionMode*/ undefined); assert.equal(result.resolvedModule, undefined); }); test("module resolver runs against snapshots or the host filesystem", async () => { - const packageJson = toRootedFilePath("/node_modules/pkg/package.json", undefined); - const packageB = toRootedFilePath("/node_modules/pkg/b.d.ts", undefined); + const packageJson = toRootedFilePath("/node_modules/pkg/package.json", /*currentDirectory*/ undefined); + const packageB = toRootedFilePath("/node_modules/pkg/b.d.ts", /*currentDirectory*/ undefined); const { api: disposableAPI, fs } = spawnAPIWithFS({ [packageJson]: JSON.stringify({ name: "pkg", version: "1.0.0", types: "a.d.ts" }), "/node_modules/pkg/a.d.ts": `export declare const value: "a";`, @@ -1256,12 +1259,12 @@ describe("API", { concurrency }, () => { }); const firstSnapshot = await api.createSnapshot(); assert.equal( - (await resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/a.d.ts", undefined), + (await resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/a.d.ts", /*currentDirectory*/ undefined), ); - fs.writeFile!(packageJson, JSON.stringify({ name: "pkg", version: "1.0.0", types: "b.d.ts" })); - fs.writeFile!(packageB, `export declare const value: "b";`); + fs.writeFile(packageJson, JSON.stringify({ name: "pkg", version: "1.0.0", types: "b.d.ts" })); + fs.writeFile(packageB, `export declare const value: "b";`); const secondSnapshot = await firstSnapshot.update({ fileNotifications: { changed: [packageJson], @@ -1270,12 +1273,12 @@ describe("API", { concurrency }, () => { }); assert.equal( - (await resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/a.d.ts", undefined), + (await resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/a.d.ts", /*currentDirectory*/ undefined), ); assert.equal( - (await resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: secondSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/b.d.ts", undefined), + (await resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: secondSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/b.d.ts", /*currentDirectory*/ undefined), ); assert.equal( (await resolver.resolveModuleName("pkg", "/src")).resolvedModule?.resolvedFileName, @@ -1456,7 +1459,7 @@ import "pkg/feature";`, }); assert.deepEqual( - [...await snapshot.operation.createdPrograms![0].getSourceFileNames()].sort(), + [...await snapshot.operation.createdPrograms[0].getSourceFileNames()].sort(), ["/node_modules/@types/resolver-types/index.d.ts", "/node_modules/pkg/dist/feature.d.ts", "/src/index.ts"], ); }); @@ -1614,7 +1617,8 @@ declare module "augmentation" {}`, }; // @ts-expect-error raw path strings are not finalized compiler options const _finalizedOptions: CompilerOptions = rawOptions; - const _rawOptions: RawCompilerOptions = undefined! as CompilerOptions; + const finalizedOptions: CompilerOptions = undefined!; + const _rawOptions: RawCompilerOptions = finalizedOptions; const program = await api.createProgram(["/src/index.ts", "/src/component.vue"], rawOptions); const compilerOptions: CompilerOptions = program.getCompilerOptions(); @@ -1624,14 +1628,14 @@ declare module "augmentation" {}`, { noLib: true, allowNonTsExtensions: true, - outDir: toRootedDirectoryPath(resolve(serverCurrentDirectory, "dist"), undefined), + outDir: toRootedDirectoryPath(resolve(serverCurrentDirectory, "dist"), /*currentDirectory*/ undefined), paths: { "*a": ["/src/first.ts"], "*": ["/src/fallback.ts"] }, rootDirs: [ - toRootedDirectoryPath(resolve(serverCurrentDirectory, "src"), undefined), - toRootedDirectoryPath(resolve(serverCurrentDirectory, "generated"), undefined), + toRootedDirectoryPath(resolve(serverCurrentDirectory, "src"), /*currentDirectory*/ undefined), + toRootedDirectoryPath(resolve(serverCurrentDirectory, "generated"), /*currentDirectory*/ undefined), ], suppressOutputPathCheck: true, - tsBuildInfoFile: toRootedFilePath(resolve(serverCurrentDirectory, "cache/build.tsbuildinfo"), undefined), + tsBuildInfoFile: toRootedFilePath(resolve(serverCurrentDirectory, "cache/build.tsbuildinfo"), /*currentDirectory*/ undefined), } satisfies CompilerOptions, ); assert.equal((await program.getSemanticDiagnostics("/src/index.ts")).length, 0); @@ -1793,7 +1797,7 @@ describe("API - automatic batching", { concurrency }, () => { await using program = await api.createProgram(["/src/main.ts"], { noLib: true }); await using empty = await api.createProgram([], { noLib: true }); // @ts-ignore -- Internal client requests are exercised by source tests. - const client = api["client"]; + const client = api.client; const request = context.mock.method(client, "apiRequest"); const [statistics, repeated, emptyStatistics] = await Promise.all([ @@ -1819,7 +1823,7 @@ describe("API - automatic batching", { concurrency }, () => { await using api = spawnAPI({ "/src/main.ts": "export const value = 1;" }); await using program = await api.createProgram(["/src/main.ts"], { noLib: true }); // @ts-ignore -- Internal client requests are exercised by source tests. - const client = api["client"]; + const client = api.client; const request = context.mock.method(client, "apiRequest"); const error = new Error("Statistics request failed"); request.mock.mockImplementationOnce(() => Promise.reject(error)); @@ -2037,8 +2041,8 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); }); test("returns diagnostics in build response information", async () => { @@ -2088,8 +2092,9 @@ describe("BuildOrchestrator", () => { const cleanResp1 = await orchestrator.clean("/a/tsconfig.json"); assert.equal(cleanResp1.status, 0); - assert.deepEqual(cleanResp1.diagnostics, undefined); - assert.deepEqual(cleanResp1.filesDeleted!.sort(), [ + assert.deepEqual(cleanResp1.diagnostics, /*expected*/ undefined); + cleanResp1.filesDeleted!.sort(); + assert.deepEqual(cleanResp1.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -2098,14 +2103,15 @@ describe("BuildOrchestrator", () => { assert.equal(cleanResp1.statistics.ProjectsBuilt, 0); const buildResp1 = await orchestrator.build("/a/tsconfig.json"); assert.equal(buildResp1.status, 0); - assert.deepEqual(buildResp1.diagnostics, undefined); + assert.deepEqual(buildResp1.diagnostics, /*expected*/ undefined); assert.equal(buildResp1.statistics.Projects, 1); assert.equal(buildResp1.statistics.ProjectsBuilt, 1); const cleanRefResp = await orchestrator.cleanReferences("/c/tsconfig.json"); assert.equal(cleanRefResp.status, 0); - assert.deepEqual(cleanRefResp.diagnostics, undefined); - assert.deepEqual(cleanRefResp.filesDeleted!.sort(), [ + assert.deepEqual(cleanRefResp.diagnostics, /*expected*/ undefined); + cleanRefResp.filesDeleted!.sort(); + assert.deepEqual(cleanRefResp.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -2117,12 +2123,13 @@ describe("BuildOrchestrator", () => { assert.equal(cleanRefResp.statistics.ProjectsBuilt, 0); const buildRefsResp = await orchestrator.buildReferences("/c/tsconfig.json"); assert.equal(buildRefsResp.status, 0); - assert.deepEqual(buildRefsResp.diagnostics, undefined); + assert.deepEqual(buildRefsResp.diagnostics, /*expected*/ undefined); const cleanResp2 = await orchestrator.clean(); assert.equal(cleanResp2.status, 0); - assert.deepEqual(cleanResp2.diagnostics, undefined); - assert.deepEqual(cleanResp2.filesDeleted!.sort(), [ + assert.deepEqual(cleanResp2.diagnostics, /*expected*/ undefined); + cleanResp2.filesDeleted!.sort(); + assert.deepEqual(cleanResp2.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -2137,7 +2144,7 @@ describe("BuildOrchestrator", () => { assert.equal(cleanResp2.statistics.ProjectsBuilt, 0); const buildResp2 = await orchestrator.build(); assert.equal(buildResp2.status, 0); - assert.deepEqual(buildResp2.diagnostics, undefined); + assert.deepEqual(buildResp2.diagnostics, /*expected*/ undefined); assert.equal(buildResp2.statistics.Projects, 3); assert.equal(buildResp2.statistics.ProjectsBuilt, 3); }); @@ -2157,15 +2164,16 @@ describe("BuildOrchestrator", () => { const response = await orchestrator.clean(); assert.equal(response.status, 0); - assert.deepEqual(response.diagnostics, undefined); - assert.deepEqual(response.filesDeleted!.sort(), [ + assert.deepEqual(response.diagnostics, /*expected*/ undefined); + response.filesDeleted!.sort(); + assert.deepEqual(response.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", ]); assert.equal(response.statistics.Projects, 1); assert.equal(response.statistics.ProjectsBuilt, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.d.ts", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.d.ts", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("rebuilds projects after multiple file system changes", async () => { @@ -2178,24 +2186,24 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 10;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 10;`); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 20;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 20;`); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 20/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 20/); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 100;`); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 200;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 100;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 200;`); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 100/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 200/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 100/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 200/); }); test("clean removes build outputs", async () => { @@ -2208,13 +2216,13 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((await orchestrator.clean()).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("builds and cleans selected projects after file system changes", async () => { @@ -2227,35 +2235,35 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build("/a/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 10;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 10;`); assert.equal((await orchestrator.build("/b/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 20;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 20;`); assert.equal((await orchestrator.clean("/a/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.match(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))!, /export const c = 3/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), /export const c = 3/); assert.equal((await orchestrator.clean("/b/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.match(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))!, /export const c = 3/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), /export const c = 3/); - fs.writeFile!(toRootedFilePath("/b/dist/index.js", undefined), `export const b = 2`); + fs.writeFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined), `export const b = 2`); assert.equal((await orchestrator.clean("/b/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("builds only references of a selected project", async () => { @@ -2263,7 +2271,7 @@ describe("BuildOrchestrator", () => { ...files, }); await using api = disposableApi; - const options = await api.parseCommandLine([]); + await api.parseCommandLine([]); // @ts-ignore -- Internal API exercised by source tests. const orchestrator = await api.createBuildOrchestrator( ["/c/tsconfig.json"], @@ -2271,9 +2279,9 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.buildReferences("/c/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("cleans only references of a selected project", async () => { @@ -2288,22 +2296,22 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((await orchestrator.cleanReferences("/c/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((await orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((await orchestrator.cleanReferences()).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); }); test("handles invalidated projects and cleans the last built configuration", async () => { @@ -2328,24 +2336,24 @@ describe("BuildOrchestrator", () => { ); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined))!, /export const d = 4/); + assert.match(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), /export const d = 4/); - fs.writeFile!( - toRootedFilePath("/d/tsconfig.json", undefined), + fs.writeFile( + toRootedFilePath("/d/tsconfig.json", /*currentDirectory*/ undefined), JSON.stringify({ compilerOptions: { composite: true, outDir: "lib", rootDir: "src" }, files: ["src/index.ts"], }), ); - fs.writeFile!(toRootedFilePath("/d/lib/index.js", undefined), `export const d = 40;`); + fs.writeFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined), `export const d = 40;`); assert.equal((await orchestrator.clean("/d/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/d/lib/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined))); assert.equal((await orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/d/lib/index.js", undefined))!, /export const d = 4/); - assert.equal(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined)), /export const d = 4/); + assert.equal(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); }); @@ -2434,7 +2442,7 @@ test(); const project = snapshot.getConfiguredProject("/tsconfig.json")!; const sourceFile = await project.program.getSourceFile("/src/main.ts"); assert.ok(sourceFile); - const nodes: Array = []; + const nodes: Node[] = []; sourceFile.forEachChild(node => { if (isExpressionStatement(node) && isCallExpression(node.expression) && node.expression.typeArguments) { nodes.push(node.expression.typeArguments[0]); @@ -3017,9 +3025,9 @@ describe("SourceFile", { concurrency }, () => { "/src/dependency.ts": `export const value = 1;`, }); await using program = await api.createProgram(["/src/main.ts"], { noLib: true }); - assert.ok(!("getTypeChecker" in program)); - assert.ok(!("getResolvedProjectReferences" in program)); - assert.ok(!("getSourceFiles" in program)); + assert.ok(!Reflect.has(program, "getTypeChecker")); + assert.ok(!Reflect.has(program, "getResolvedProjectReferences")); + assert.ok(!Reflect.has(program, "getSourceFiles")); assert.deepEqual(await program.getRootFileNames(), ["/src/main.ts"]); assert.deepEqual(await program.getSourceFileNames(), ["/src/dependency.ts", "/src/main.ts"]); assert.equal(await program.getProjectReferences(), undefined); @@ -3107,7 +3115,7 @@ export const other: { value: string } = box;`, const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); const project = snapshot.getConfiguredProject("/tsconfig.json")!; for (const method of ["containsFile", "getFileNames", "getRootFiles", "hasRoots", "isRoot", "hasConfigFile", "getSourceFile"]) { - assert.ok(!(method in project), `Project should not expose ${method}`); + assert.ok(!Reflect.has(project, method), `Project should not expose ${method}`); } }); @@ -3139,7 +3147,7 @@ export const other: { value: string } = box;`, typescript: { contentMapper: { exec: [process.execPath, "--input-type=module", "--eval", mapperScript] } }, }), ); - const configFileName = toRootedFilePath(join(directory, "tsconfig.json"), undefined); + const configFileName = toRootedFilePath(join(directory, "tsconfig.json"), /*currentDirectory*/ undefined); writeFileSync( configFileName, JSON.stringify({ @@ -3153,7 +3161,7 @@ export const other: { value: string } = box;`, await using api = new API({ cwd: directory, runExternalCode: true }); const snapshot = await api.createSnapshot({ openProjects: [configFileName] }); const program = snapshot.getConfiguredProject(configFileName)!.program; - const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), undefined); + const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), /*currentDirectory*/ undefined); assert.equal(existsSync(supplementalFileName), false); assert.ok(await program.getSourceFile(supplementalFileName)); }); @@ -3313,8 +3321,8 @@ export const other: { value: string } = box;`, (function walk(node: Node): void { visited.push({ kind: node.kind, pos: node.pos, end: node.end }); node.forEachChild(walk, (nodes: NodeArray) => { - for (let i = 0; i < nodes.length; i++) { - walk(nodes[i]); + for (const node of nodes) { + walk(node); } return undefined; }); @@ -3383,6 +3391,7 @@ describe("API objects", { concurrency }, () => { test("template unicode escapes", async () => { await using api = spawnAPI({ "/tsconfig.json": "{}", + // eslint-disable-next-line no-template-curly-in-string -- This string is TypeScript source. "/src/index.ts": "`\\ud800${0}\\udc00`", }); @@ -3479,7 +3488,7 @@ describe("Multiple snapshots", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file and create a new snapshot with the change - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = "changed";`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = "changed";`); const snap2 = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/foo.ts"] }, @@ -3515,7 +3524,7 @@ describe("Multiple snapshots", { concurrency }, () => { const snap1 = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); // Add a brand new file - fs.writeFile!(toRootedFilePath("/src/bar.ts", undefined), `export const bar = true;`); + fs.writeFile(toRootedFilePath("/src/bar.ts", /*currentDirectory*/ undefined), `export const bar = true;`); const snap2 = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { created: ["/src/bar.ts"] }, @@ -3543,7 +3552,7 @@ describe("Multiple snapshots", { concurrency }, () => { ]; for (const version of versions) { - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), version); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), version); const snap = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/foo.ts"] }, @@ -3569,7 +3578,7 @@ describe("Multiple snapshots", { concurrency }, () => { const baseFirst = await base.getConfiguredProject("/first/tsconfig.json")!.program.getSourceFile("/first/index.ts"); const baseSecondProject = base.getConfiguredProject("/second/tsconfig.json")!; - fs.writeFile!(toRootedFilePath("/first/index.ts", undefined), `export const first = 2;`); + fs.writeFile(toRootedFilePath("/first/index.ts", /*currentDirectory*/ undefined), `export const first = 2;`); const updated = await base.update({ fileNotifications: { changed: ["/first/index.ts"] }, ensurePrograms: [base.getConfiguredProject("/first/tsconfig.json")!.id], @@ -3614,15 +3623,15 @@ describe("Multiple snapshots", { concurrency }, () => { assert.equal(created.getProjects().length, 3); const configuredProjectId: ConfiguredProjectId = created.getConfiguredProject("/configured/tsconfig.json")!.id; void configuredProjectId; - assert.strictEqual(created.operation.openedFiles![0].project, created.getProject(created.operation.openedFiles![0].project.id)); - assert.strictEqual(created.operation.openedFiles![1].project, created.getConfiguredProject("/configured/tsconfig.json")); + assert.strictEqual(created.operation.openedFiles[0].project, created.getProject(created.operation.openedFiles[0].project.id)); + assert.strictEqual(created.operation.openedFiles[1].project, created.getConfiguredProject("/configured/tsconfig.json")); for (const project of created.getProjects()) { assert.equal(project.dirty, false, `${project.id} should be ensured when opened or created`); } - fs.writeFile!(toRootedFilePath("/configured/index.ts", undefined), `export const configured = 2;`); - fs.writeFile!(toRootedFilePath("/inferred.ts", undefined), `export const inferred = 2;`); - fs.writeFile!(toRootedFilePath("/synthetic.ts", undefined), `export const synthetic = 2;`); + fs.writeFile(toRootedFilePath("/configured/index.ts", /*currentDirectory*/ undefined), `export const configured = 2;`); + fs.writeFile(toRootedFilePath("/inferred.ts", /*currentDirectory*/ undefined), `export const inferred = 2;`); + fs.writeFile(toRootedFilePath("/synthetic.ts", /*currentDirectory*/ undefined), `export const synthetic = 2;`); const dirty = await created.update({ fileNotifications: { changed: ["/configured/index.ts", "/inferred.ts", "/synthetic.ts"] }, }); @@ -3685,7 +3694,7 @@ describe("Source file caching", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file in the VFS - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = 100;`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = 100;`); // Notify the server about the change const snap2 = await api.createSnapshot({ @@ -3709,7 +3718,7 @@ describe("Source file caching", { concurrency }, () => { assert.ok(sf1); // Mutate a different file - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = 999;`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = 999;`); // Notify the server about the change to foo.ts only const snap2 = await api.createSnapshot({ @@ -3750,7 +3759,7 @@ describe("Source file caching", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = "hello";`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = "hello";`); // Use invalidateAll to force re-fetch const snap2 = await api.createSnapshot({ @@ -3790,7 +3799,7 @@ describe("Source file caching", { concurrency }, () => { assert.ok(type1.flags & TypeFlags.Number); // Snapshot 2: change a different file - fs.writeFile!(toRootedFilePath("/src/other.ts", undefined), `export const x = 2;`); + fs.writeFile(toRootedFilePath("/src/other.ts", /*currentDirectory*/ undefined), `export const x = 2;`); const snap2 = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/other.ts"] }, @@ -4381,7 +4390,7 @@ export class Cache { const sigs = await project.checker.getSignaturesOfType(type, SignatureKind.Call); assert.ok(sigs.length > 0); const thisParam = await sigs[0].getThisParameter(); - assert.strictEqual(thisParam, undefined, "add() has no explicit this parameter"); + assert.strictEqual(thisParam, /*expected*/ undefined, "add() has no explicit this parameter"); }); test("Signature.getThisParameter() returns symbol for explicit this parameter", async () => { @@ -4418,7 +4427,7 @@ export class Cache { const sigs = await project.checker.getSignaturesOfType(type, SignatureKind.Call); assert.ok(sigs.length > 0); const target = await sigs[0].getTarget(); - assert.strictEqual(target, undefined, "add() is not an instantiated signature"); + assert.strictEqual(target, /*expected*/ undefined, "add() is not an instantiated signature"); }); test("Signature.getTarget() returns the generic source signature for an instantiated call", async () => { @@ -4548,10 +4557,11 @@ export const value = 1; const project = snapshot.getConfiguredProject("/tsconfig.json")!; const sourceFile = await project.program.getSourceFile("/src/mod.ts"); assert.ok(sourceFile); - await using retained = await api.retainSourceFile(sourceFile); + await using _retained = await api.retainSourceFile(sourceFile); const animal = await project.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); const storage = animal["storage"]; + // eslint-disable-next-line local/no-in-operator -- Narrow the ownership union. assert.ok("owner" in storage); assert.strictEqual(storage.owner.api, api); assert.deepEqual(Object.keys(storage.owner).sort(), ["api", "record"]); @@ -4785,7 +4795,7 @@ second;`; const animal = await firstSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); - fs.writeFile!(toRootedFilePath("/src/other.ts", undefined), `export const other = 2;`); + fs.writeFile(toRootedFilePath("/src/other.ts", /*currentDirectory*/ undefined), `export const other = 2;`); const secondSnapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/other.ts"] } }); const type = await secondSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getTypeOfSymbol(animal); assert.ok(type); @@ -4799,7 +4809,7 @@ second;`; const animal = await firstSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); - fs.writeFile!(toRootedFilePath("/src/mod.ts", undefined), `${symbolFiles["/src/mod.ts"]}\nexport const added = 2;`); + fs.writeFile(toRootedFilePath("/src/mod.ts", /*currentDirectory*/ undefined), `${symbolFiles["/src/mod.ts"]}\nexport const added = 2;`); const secondSnapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/mod.ts"] } }); const secondProject = secondSnapshot.getConfiguredProject("/tsconfig.json")!; await assert.rejects(secondProject.checker.getTypeOfSymbol(animal), /source file is not part of the requested program/); // @sync: assert.throws(() => secondProject.checker.getTypeOfSymbol(animal), /source file is not part of the requested program/); @@ -4867,7 +4877,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("TypeReference.getTarget() returns the generic target", async () => { const { type, api: disposableAPI } = await getTypeAtName(spawnAPI(typeFiles), "arr:"); - await using api = disposableAPI; + await using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Object); const ref = type as TypeReference; @@ -4890,7 +4900,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("UnionOrIntersectionType.getTypes() returns union members", async () => { const { type, api: disposableAPI } = await getTypeAtName(spawnAPI(typeFiles), "union:"); - await using api = disposableAPI; + await using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Union); const union = type as UnionOrIntersectionType; @@ -4903,7 +4913,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("UnionOrIntersectionType.getTypes() returns intersection members", async () => { const { type, api: disposableAPI } = await getTypeAtName(spawnAPI(typeFiles), "intersection:"); - await using api = disposableAPI; + await using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Intersection); const inter = type as UnionOrIntersectionType; @@ -5048,7 +5058,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("TemplateLiteralType.texts and getTypes()", async () => { const { type, api: disposableAPI } = await getTypeAtName(spawnAPI(typeFiles), "tpl:"); - await using api = disposableAPI; + await using _api = disposableAPI; assert.ok(type.flags & TypeFlags.TemplateLiteral, `Expected TemplateLiteralType, got flags ${type.flags}`); const tpl = type as TemplateLiteralType; @@ -5113,7 +5123,7 @@ array([]); assert.equal(type.isTupleType(), true); assert.equal(type.isTupleTypeTarget(), false); assert.ok(type.isTupleType()); - assert.equal(Reflect.get(type, "fixedLength"), undefined); + assert.equal((type as { fixedLength?: unknown; }).fixedLength, undefined); const target = await type.getTarget(); assert.ok(target.objectFlags & ObjectFlags.Tuple); @@ -5387,7 +5397,7 @@ describe("Checker - literal and nullable type getters", { concurrency }, () => { assert.ok(withBoth.flags & TypeFlags.Union, `Expected union, got flags ${withBoth.flags}`); // Adding no flags should just return the original type unchanged. - const withNeither = await project.checker.getNullableType(stringType, 0 as TypeFlags); + const withNeither = await project.checker.getNullableType(stringType, 0); assert.equal(withNeither.id, stringType.id); }); @@ -5826,6 +5836,7 @@ describe("readFile callback semantics", { concurrency }, () => { ...createVirtualFileSystem({ "/tsconfig.json": "{}", }), + // eslint-disable-next-line no-restricted-syntax -- A null result must not mean a missing file. readFile: (() => null) as unknown as FileSystemCallbacks["readFile"], }; await using api = new API({ cwd: "/", fs }); @@ -5858,7 +5869,7 @@ describe("readFile callback semantics", { concurrency }, () => { await using snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); assert.ok( (await snapshot.getConfiguredProject("/tsconfig.json")!.program.getSourceFileNames()) - .includes(toRootedFilePath("/node_modules/pkg/index.d.ts", undefined)), + .includes(toRootedFilePath("/node_modules/pkg/index.d.ts", /*currentDirectory*/ undefined)), ); } }); @@ -6035,19 +6046,19 @@ describe("updateSnapshot file systems", { concurrency }, () => { const fs: FileSystemCallbacks = { readFile: path => { callbackCalls.push(`readFile:${path}`); - return host.readFile!(path); + return host.readFile(path); }, fileExists: path => { callbackCalls.push(`fileExists:${path}`); - return host.fileExists!(path); + return host.fileExists(path); }, directoryExists: path => { callbackCalls.push(`directoryExists:${path}`); - return host.directoryExists!(path); + return host.directoryExists(path); }, getAccessibleEntries: path => { callbackCalls.push(`getAccessibleEntries:${path}`); - return host.getAccessibleEntries!(path); + return host.getAccessibleEntries(path); }, realpath: path => { callbackCalls.push(`realpath:${path}`); @@ -6061,7 +6072,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { }, writeFile: (path, content) => { callbackCalls.push(`writeFile:${path}`); - host.writeFile!(path, content); + host.writeFile(path, content); }, removeFile: path => { callbackCalls.push(`removeFile:${path}`); @@ -6160,11 +6171,11 @@ describe("updateSnapshot file systems", { concurrency }, () => { ...host, readFile: path => { readFileCalls.push(path); - return host.readFile!(path); + return host.readFile(path); }, getAccessibleEntries: path => { directoryCalls.push(path); - return host.getAccessibleEntries!(path); + return host.getAccessibleEntries(path); }, }; await using api = new API({ @@ -6415,7 +6426,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { const programId = target.operation.createdPrograms[0].id; const originalFile = await target.getProgram(programId)!.getSourceFile("/index.ts"); assert.equal(originalFile!.text, "export const value = 1;"); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); await using source = await api.createSnapshot({ fileSystem: createFileSystemLayer([["/index.ts", "export const value = 2;"]]), }); @@ -6463,7 +6474,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { }); const programId = original.operation.createdPrograms[0].id; await using target = await original.update({}); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); const changes = { fileNotifications: { invalidateAll: true }, ensurePrograms: true } as const; await using updated = await original.update(changes); assert.equal((await updated.getProgram(programId)!.getSourceFile("/index.ts"))!.text, "export const value = 2;"); @@ -6521,7 +6532,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { await using moreExtras = await extras.update({ fileSystem: createFileSystemLayer([["/src/second.ts", "export const second = true;"]]), }); - fs.writeFile!(toRootedFilePath("/src/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/src/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); await using newOriginal = await original.update({ openProjects: ["/other/tsconfig.json"], ensurePrograms: true, @@ -6713,7 +6724,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { const program = snapshot.getConfiguredProject("/tsconfig.json")!.program; const result = await program.emit(); assert.equal(result.fileSystem, undefined); - assert.equal(host.readFile!(toRootedFilePath("/out/main.js", undefined)), `export const value = 1;\n`); + assert.equal(host.readFile(toRootedFilePath("/out/main.js", /*currentDirectory*/ undefined)), `export const value = 1;\n`); }); test("full file system can link node_modules from the host", async () => { @@ -6729,16 +6740,16 @@ describe("updateSnapshot file systems", { concurrency }, () => { ...host, directoryExists: path => { directoryExistsCalls.push(path); - return host.directoryExists!(path); + return host.directoryExists(path); }, fileExists: path => { - const exists = host.fileExists!(path); + const exists = host.fileExists(path); fileExistsCalls.push(`${path}:${exists}`); return exists; }, readFile: path => { readFileCalls.push(path); - return host.readFile!(path); + return host.readFile(path); }, }, }); @@ -7302,7 +7313,7 @@ export const n: number = 0; assert.ok(derivedType.isClassOrInterface(), "Derived should be a class/interface type"); const baseTypes = await derivedType.getBaseTypes(); assert.ok(baseTypes && baseTypes.length > 0, "class type should have base types"); - const baseSymbol = await baseTypes![0].getSymbol(); + const baseSymbol = await baseTypes[0].getSymbol(); assert.equal(baseSymbol?.name, "Base"); // A primitive type is not a class/interface, so getBaseTypes() is undefined. @@ -8031,7 +8042,7 @@ describe("Checker - TypeParameter getters", { concurrency }, () => { assert.ok(sigs.length > 0); const typeParams = await sigs[0].getTypeParameters(); assert.ok(typeParams.length > 0, "Should have type parameters"); - const typeParam = typeParams[0] as TypeParameter; + const typeParam = typeParams[0]; const constraint = await typeParam.getConstraint(); assert.ok(constraint); @@ -8060,7 +8071,7 @@ describe("Checker - TypeParameter getters", { concurrency }, () => { assert.ok(sigs.length > 0); const typeParams = await sigs[0].getTypeParameters(); assert.ok(typeParams.length > 0, "Should have type parameters"); - const typeParam = typeParams[0] as TypeParameter; + const typeParam = typeParams[0]; assert.equal(await typeParam.getConstraint(), undefined); assert.equal(await typeParam.getDefault(), undefined); @@ -8895,7 +8906,7 @@ describe("FreshableType - getFreshType and getRegularType", { concurrency }, () assert.ok(regular.flags & TypeFlags.Enum, "Regular enum type should also have TypeFlags.Enum"); assert.notEqual(regular.id, type.id, "Regular type should be distinct from the fresh type"); // Round-trip: regular → getFreshType() → back to the original fresh type - const backToFresh = await (regular as FreshableType).getFreshType(); + const backToFresh = await regular.getFreshType(); assert.ok(backToFresh); assert.equal(backToFresh.id, type.id, "Round-trip through regular/fresh returns the original type"); }); @@ -9056,7 +9067,7 @@ export const obj = { m: 1, s: "hi", b: true }; await using lease = await api.createSourceFile("/test.ts", "/** leading comment */\nfoo();\n/* @__PURE__ */ baz();\n"); const { sourceFile } = lease; const added = createExpressionStatement( - createCallExpression(createIdentifier("bar"), undefined, undefined, [createStringLiteral("x", TokenFlags.None)], NodeFlags.None), + createCallExpression(createIdentifier("bar"), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [createStringLiteral("x", TokenFlags.None)], NodeFlags.None), ); const updated = updateSourceFile(sourceFile, [added, ...sourceFile.statements], sourceFile.endOfFileToken); const expected = 'bar("x");\n/** leading comment */\nfoo();\n/* @__PURE__ */ baz();\n'; @@ -9104,7 +9115,7 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createUnionTypeNode([ createKeywordTypeNode(SyntaxKind.StringKeyword), createKeywordTypeNode(SyntaxKind.NumberKeyword), @@ -9117,17 +9128,17 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const param = createParameterDeclaration( - undefined, - undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, createIdentifier("x"), - undefined, + /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), - undefined, + /*initializer*/ undefined, ); const node = createFunctionTypeNode( - undefined, + /*typeParameters*/ undefined, [param], createKeywordTypeNode(SyntaxKind.NumberKeyword), ); @@ -9139,7 +9150,7 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createTypeReferenceNode(createIdentifier("Array"), [ createKeywordTypeNode(SyntaxKind.StringKeyword), ]); @@ -9151,7 +9162,7 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createArrayTypeNode(createKeywordTypeNode(SyntaxKind.NumberKeyword)); const text = await api.printer.printNode(node); assert.strictEqual(text, "number[]"); @@ -9188,7 +9199,7 @@ export const obj = { m: 1, s: "hi", b: true }; const symbol = await checker.getSymbolAtPosition("/main.ts", 13); assert.strictEqual(symbol?.name, "x"); const type = await checker.getTypeOfSymbol(symbol); - assert.strictEqual(await checker.typeToTypeNode(type, await project.program.getSourceFile("/main.ts")), undefined); + assert.strictEqual(await checker.typeToTypeNode(type, await project.program.getSourceFile("/main.ts")), /*expected*/ undefined); }); test("visitEachChild on typeToTypeNode result with keyword types", async () => { @@ -9385,7 +9396,7 @@ export const obj = { m: 1, s: "hi", b: true }; valueType: info.valueType, isReadonly: false, }, - undefined, + /*enclosingDeclaration*/ undefined, NodeBuilderFlags.WriteArrayAsGenericType, ); assert.ok(synthesized); @@ -9458,7 +9469,7 @@ export const obj = { m: 1, s: "hi", b: true }; assert.ok(symbol); const type = await checker.getTypeOfSymbol(symbol); assert.ok(type); - const text = await checker.typeToString(type, undefined, TypeFormatFlags.WriteArrayAsGenericType); + const text = await checker.typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType); assert.strictEqual(text, "(name: string) => Array"); }); @@ -9497,14 +9508,14 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const stringProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); - const numberProp = createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!); + const stringProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); + const numberProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([stringProp, numberProp]); - emitContext.addSyntheticLeadingComment(typeLiteral, SyntaxKind.SingleLineCommentTrivia, " top", true, false); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a", true, false); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a again", true, false); - emitContext.addSyntheticTrailingComment(numberProp, SyntaxKind.MultiLineCommentTrivia, " nested b ", false, false); + emitContext.addSyntheticLeadingComment(typeLiteral, SyntaxKind.SingleLineCommentTrivia, " top", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a again", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticTrailingComment(numberProp, SyntaxKind.MultiLineCommentTrivia, " nested b ", /*hasTrailingNewLine*/ false, /*hasLeadingNewLine*/ false); assert.deepStrictEqual( emitContext.getSyntheticLeadingComments(stringProp)?.map(c => c.text), @@ -9512,9 +9523,9 @@ export const obj = { m: 1, s: "hi", b: true }; ); assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(numberProp)?.map(c => c.text), [" nested b "]); - assert.deepStrictEqual(emitContext.getSyntheticLeadingComments(numberProp), undefined); - assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(stringProp), undefined); - assert.strictEqual(emitContext.getSyntheticLeadingComments(createIdentifier("untouched")), undefined); + assert.deepStrictEqual(emitContext.getSyntheticLeadingComments(numberProp), /*expected*/ undefined); + assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(stringProp), /*expected*/ undefined); + assert.strictEqual(emitContext.getSyntheticLeadingComments(createIdentifier("untouched")), /*expected*/ undefined); assert.strictEqual(emitContext.getEmitFlags(typeLiteral), 0); const text = await api.printer.printNode(typeLiteral, { emitContext }); @@ -9534,10 +9545,10 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const stringProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); + const stringProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([stringProp]); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " will be replaced", true, false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " will be replaced", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); emitContext.setSyntheticLeadingComments(stringProp, [ { kind: SyntaxKind.SingleLineCommentTrivia, text: " bulk leading 1", hasTrailingNewLine: true, hasLeadingNewLine: false }, { kind: SyntaxKind.SingleLineCommentTrivia, text: " bulk leading 2", hasTrailingNewLine: true, hasLeadingNewLine: false }, @@ -9586,8 +9597,8 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const typeLiteral = createTypeLiteralNode([ - createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!), - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); assert.strictEqual(await api.printer.printNode(typeLiteral), "{\n a: string;\n b: number;\n}"); @@ -9606,7 +9617,7 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const multiLineObject = createObjectLiteralExpression([ - createPropertyAssignment(undefined, createIdentifier("a"), undefined, undefined!, createNumericLiteral("1", 0)), + createPropertyAssignment(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0)), ]); assert.strictEqual(await api.printer.printNode(multiLineObject), "{ a: 1 }"); @@ -9627,8 +9638,8 @@ export const obj = { m: 1, s: "hi", b: true }; assert.strictEqual(EmitFlags.NoTokenSourceMaps, EmitFlags.NoTokenLeadingSourceMaps | EmitFlags.NoTokenTrailingSourceMaps); const typeLiteral = createTypeLiteralNode([ - createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!), - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); const emitContext = api.printer.createEmitContext(); assert.strictEqual(emitContext.getEmitFlags(typeLiteral), EmitFlags.None); @@ -9645,12 +9656,12 @@ export const obj = { m: 1, s: "hi", b: true }; await using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const commentedProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); + const commentedProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([ commentedProp, - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); - emitContext.addSyntheticLeadingComment(commentedProp, SyntaxKind.SingleLineCommentTrivia, " only on a", true, false); + emitContext.addSyntheticLeadingComment(commentedProp, SyntaxKind.SingleLineCommentTrivia, " only on a", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); // Both members are part of the same printed tree. The comment attached to // `commentedProp` should not leak onto its sibling. @@ -9673,7 +9684,7 @@ export const obj = { m: 1, s: "hi", b: true }; assert(sourceFile); const emitContext = api.printer.createEmitContext(); - emitContext.addSyntheticLeadingComment(sourceFile.statements[0], SyntaxKind.SingleLineCommentTrivia, " printFile honors emitContext", true, false); + emitContext.addSyntheticLeadingComment(sourceFile.statements[0], SyntaxKind.SingleLineCommentTrivia, " printFile honors emitContext", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); const text = await api.printer.printFile(sourceFile, { emitContext }); assert.match(text, /printFile honors emitContext/); @@ -9709,10 +9720,10 @@ describe("Program - selected file emit", { concurrency }, () => { "/src/b.js", "/src/b.js.map", ]); - const outputFileName = toRootedFilePath("/src/a.js", undefined); + const outputFileName = toRootedFilePath("/src/a.js", /*currentDirectory*/ undefined); assert.equal(result.outputFiles.get(outputFileName)?.sourceFileName, "/src/a.ts"); assert.match(result.outputFiles.get(outputFileName)!.text, /export const a = 1/); - assert.equal(fs.readFile(toRootedFilePath("/src/a.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/src/a.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("getDeclarationEmit forces declarations and declaration maps", async () => { @@ -9729,8 +9740,8 @@ describe("Program - selected file emit", { concurrency }, () => { "/src/b.d.ts", "/src/b.d.ts.map", ]); - assert.equal(result.outputFiles.get(toRootedFilePath("/src/a.d.ts", undefined))?.sourceFileName, "/src/a.ts"); - assert.equal(fs.readFile(toRootedFilePath("/src/a.d.ts", undefined)), serverFS.useOS); + assert.equal(result.outputFiles.get(toRootedFilePath("/src/a.d.ts", /*currentDirectory*/ undefined))?.sourceFileName, "/src/a.ts"); + assert.equal(fs.readFile(toRootedFilePath("/src/a.d.ts", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("selected file emit accepts empty arrays", async () => { @@ -9755,9 +9766,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("x"), undefined, undefined, createNumericLiteral("1", 0))], + [createVariableDeclaration(createIdentifier("x"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0))], NodeFlags.Const, ), ); @@ -9781,9 +9792,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("y"), undefined, undefined, createNumericLiteral("42", 0))], + [createVariableDeclaration(createIdentifier("y"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("42", 0))], NodeFlags.Const, ), ); @@ -9806,9 +9817,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("x"), undefined, undefined, createNumericLiteral("1", 0))], + [createVariableDeclaration(createIdentifier("x"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0))], NodeFlags.Const, ), ); @@ -10038,11 +10049,11 @@ doThing(); await using api = spawnAPI(); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createTypeAliasDeclaration( [createToken(SyntaxKind.ExportKeyword)], createIdentifier("Test"), - undefined, + /*typeParameters*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), ); @@ -10230,7 +10241,7 @@ describe("Program - diagnostics", { concurrency }, () => { await assert.rejects(getSymbol(configProperty), /Cached source file not found/); // @sync: assert.throws(() => getSymbol(configProperty), /Cached source file not found/); await assert.rejects(api.getSymbol(configProperty), /Cached source file not found/); // @sync: assert.throws(() => api.getSymbol(configProperty), /Cached source file not found/); - fs.writeFile!(toRootedFilePath("/tsconfig.base.json", undefined), `{ "compilerOptions": { "strict": false } }`); + fs.writeFile(toRootedFilePath("/tsconfig.base.json", /*currentDirectory*/ undefined), `{ "compilerOptions": { "strict": false } }`); const extendedConfig = await project.program.getConfigSourceFile("/tsconfig.base.json"); assert.ok(extendedConfig); assert.equal(extendedConfig.fileName, "/tsconfig.base.json"); @@ -10451,8 +10462,8 @@ describe("getDefaultProjectForFile", { concurrency }, () => { cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), fs: { ...fs, - readFile: path => virtualFileAvailable && path === fileName ? source : fs.readFile!(path), - fileExists: path => virtualFileAvailable && path === fileName ? true : fs.fileExists!(path), + readFile: path => virtualFileAvailable && path === fileName ? source : fs.readFile(path), + fileExists: path => virtualFileAvailable && path === fileName ? true : fs.fileExists(path), }, }); const snapshot = await api.createSnapshot({ @@ -10523,7 +10534,7 @@ describe("getDefaultProjectForFile", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 1;`); // Mutate the file and notify only via fileChanges — no follow-up openFiles/closeFiles. - fs.writeFile!(toRootedFilePath("/loose.ts", undefined), `export const foo = 2;`); + fs.writeFile(toRootedFilePath("/loose.ts", /*currentDirectory*/ undefined), `export const foo = 2;`); const snapshot2 = await api.createSnapshot({ openFiles: ["/loose.ts"], fileNotifications: { changed: ["/loose.ts"] }, @@ -10636,7 +10647,7 @@ describe("Program - emit", { concurrency }, () => { await using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10654,10 +10665,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, `export const x = 1;\n`); assert.strictEqual(dts, `export declare const x: number;\n`); assert.strictEqual(js2, `export const y = 'typescript';\n`); @@ -10669,7 +10680,7 @@ describe("Program - emit", { concurrency }, () => { await using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10685,10 +10696,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, serverFS.useOS); assert.strictEqual(dts, `export declare const x: number;\n`); assert.strictEqual(js2, serverFS.useOS); @@ -10700,7 +10711,7 @@ describe("Program - emit", { concurrency }, () => { await using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = await api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10716,10 +10727,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, `export const x = 1;\n`); assert.strictEqual(dts, serverFS.useOS); assert.strictEqual(js2, `export const y = 'typescript';\n`); @@ -10737,7 +10748,7 @@ describe("Program - emit", { concurrency }, () => { "/dist/src/index.d.ts", "/dist/src/testing.d.ts", ]); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("whole-program emit includes option-controlled maps", async () => { @@ -10767,8 +10778,8 @@ describe("Program - emit", { concurrency }, () => { "/dist/src/index.d.ts.map", ]), ); - assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.js.map", undefined))); - assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.d.ts.map", undefined))); + assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.js.map", /*currentDirectory*/ undefined))); + assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.d.ts.map", /*currentDirectory*/ undefined))); const js = await project.program.emitToString(EmitOnly.OnlyJs); assert.deepEqual([...js.outputFiles.keys()], [ @@ -10802,8 +10813,8 @@ describe("Program - emit", { concurrency }, () => { assert.equal(result.emitSkipped, true); assert.ok(result.diagnostics.some(d => d.code === 1109)); assert.deepEqual(result.emittedFiles, []); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/bad.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/good.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/bad.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/good.js", /*currentDirectory*/ undefined)), serverFS.useOS); const stringResult = await project.program.emitToString(); assert.equal(stringResult.emitSkipped, true); @@ -10831,7 +10842,7 @@ describe("Program - emit", { concurrency }, () => { emitSkipped: false, outputFiles: new Map(), }); - assert.equal(fs.readFile(toRootedFilePath("/src/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/src/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("emit rejects unknown files and invalid emitOnly values", async () => { @@ -11104,7 +11115,7 @@ function spawnAPIWithFS( ): { api: API; fs: ReturnType; } { const fs = createVirtualFileSystem(files); if (onWrite) { - const writeFile = fs.writeFile!; + const writeFile = fs.writeFile; fs.writeFile = (path, content) => { onWrite(path); writeFile(path, content); diff --git a/packages/typescript/test/async/astnav.test.ts b/packages/typescript/test/async/astnav.test.ts index 1e0ba12b6085f..92022e3ef6e7d 100644 --- a/packages/typescript/test/async/astnav.test.ts +++ b/packages/typescript/test/async/astnav.test.ts @@ -71,7 +71,7 @@ function toTokenInfo(node: Node): { kind: string; pos: number; end: number; } { // Test configuration // --------------------------------------------------------------------------- -const repoRoot = resolve(import.meta.dirname!, "..", "..", "..", ".."); +const repoRoot = resolve(import.meta.dirname, "..", "..", "..", ".."); const testFile = resolve(repoRoot, "tsc/testdata/fixtures/services/mapCode.ts"); const baselineDir = resolve(repoRoot, "tsc/testdata/baselines/reference/astnav"); diff --git a/packages/typescript/test/async/transport.test.ts b/packages/typescript/test/async/transport.test.ts index 172915330c74c..91511f8aef76f 100644 --- a/packages/typescript/test/async/transport.test.ts +++ b/packages/typescript/test/async/transport.test.ts @@ -7,13 +7,73 @@ import { describe, test, } from "node:test"; +import type { AsyncTransport } from "../../src/api/async/transport.ts"; import { TransportClient } from "../../src/api/async/transportClient.ts"; +import { isSpawnOptions } from "../../src/api/options.ts"; import type { BatchRequestsParams, BatchRequestsResponse, } from "../../src/api/proto.ts"; describe("async transport", () => { + test("recognizes connection options inherited from the prototype", async () => { + class SocketOptions { + get pipe() { + return "/socket"; + } + } + assert.strictEqual(isSpawnOptions(new SocketOptions()), /*expected*/ false); + + let closed = false; + const transport: AsyncTransport = { + request() { + throw new Error("Unexpected request"); + }, + requestBinary() { + throw new Error("Unexpected binary request"); + }, + close() { + closed = true; + }, + }; + class TransportOptions { + get transport() { + return transport; + } + } + const api = new API(new TransportOptions()); + await api.close(); + assert.strictEqual(closed, /*expected*/ true); + }); + + test("handles callback results and promises with inherited then methods", async () => { + let invokeCallback = (_name: string, _payload: string): string | PromiseLike => { + throw new Error("Callback not registered"); + }; + const client = new TransportClient({ + request() { + throw new Error("Unexpected request"); + }, + requestBinary() { + throw new Error("Unexpected binary request"); + }, + registerCallback(_name, callback) { + invokeCallback = callback; + }, + unregisterCallback() {}, + close() {}, + }, /*collectTiming*/ false); + client.registerCallback("test", () => Promise.resolve({ result: "ok" })); + assert.strictEqual(await invokeCallback("test", "{}"), '{"result":"ok"}'); + client.registerCallback("test", value => value); + for (const json of ["null", "0", "false", '""']) { + assert.strictEqual(invokeCallback("test", json), json); + } + client.registerCallback("test", () => undefined); + assert.strictEqual(invokeCallback("test", "{}"), ""); + await client.close(); + }); + test("constructs an API over an injected transport", async () => { const methods: string[] = []; let batchParams: BatchRequestsParams | undefined; @@ -137,7 +197,7 @@ describe("async transport", () => { throw new Error("Unexpected binary request"); }, close() {}, - }, false); + }, /*collectTiming*/ false); const text = client.apiRequest("parseCommandLine", { commandLine: [] }); const binary = client.apiRequestBinary("getSourceFile", { snapshot: 1, @@ -152,7 +212,7 @@ describe("async transport", () => { test("can close a process client while initialization is manually batched", async () => { const api = new API({ cwd: process.cwd() }); // @ts-ignore -- Internal client transport is exercised by source tests. - await api["client"].connect(); + await api.client.connect(); const batch = api.batchContext(); const request = api.parseCommandLine([]); const rejected = assert.rejects(request, /Client is closed/); @@ -185,7 +245,7 @@ describe("async transport", () => { throw new Error("Unexpected binary request"); }, close() {}, - }, false); + }, /*collectTiming*/ false); const first = client.apiRequest("parseCommandLine", { commandLine: [] }); const batch = client.batchContext(); @@ -219,7 +279,7 @@ describe("async transport", () => { throw new Error("could not read file"); }, close() {}, - }, false); + }, /*collectTiming*/ false); const batch = client.batchContext(); const binary = client.apiRequestBinary("getSourceFile", { @@ -248,7 +308,7 @@ describe("async transport", () => { close() {}, }; - const client = new TransportClient(neverResolves, false); + const client = new TransportClient(neverResolves, /*collectTiming*/ false); const request = client.apiRequest("parseCommandLine", { commandLine: [] }); await Promise.resolve(); await client.close(); @@ -273,7 +333,7 @@ describe("async transport", () => { throw new Error("Unexpected binary request"); }, close() {}, - }, true); + }, /*collectTiming*/ true); const timing = client.getTimingInfo(); const reset = client.resetTimingInfo(); diff --git a/packages/typescript/test/browser/smoke.test.ts b/packages/typescript/test/browser/smoke.test.ts index 6409fd2585a03..6456fdd966b0a 100644 --- a/packages/typescript/test/browser/smoke.test.ts +++ b/packages/typescript/test/browser/smoke.test.ts @@ -157,14 +157,14 @@ describe("API over WebAssembly in a browser", () => { test("runs the async and sync APIs in Chromium", async () => { const page = await browser.newPage(); await page.goto(origin); - const result = await page.evaluate(() => Reflect.get(globalThis, "result")); + const result = await page.evaluate(() => (globalThis as { result?: unknown; }).result); assert.deepStrictEqual(result, ["42", "42", 1]); }); test("runs the built async and sync API entries without bundling", async () => { const page = await browser.newPage(); await page.goto(`${origin}/unbundled`); - const result = await page.evaluate(() => Reflect.get(globalThis, "result")); + const result = await page.evaluate(() => (globalThis as { result?: unknown; }).result); assert.deepStrictEqual(result, ["42", "42", 1]); }); }); diff --git a/packages/typescript/test/diagnosticFormatter.test.ts b/packages/typescript/test/diagnosticFormatter.test.ts index e5e884ba1e754..9314e1ea40ee5 100644 --- a/packages/typescript/test/diagnosticFormatter.test.ts +++ b/packages/typescript/test/diagnosticFormatter.test.ts @@ -26,7 +26,7 @@ describe("sortAndDeduplicateDiagnostics", () => { const diagnostic: Diagnostic = { pos: -1, end: -1, code: 1, category: 1, text: "Error" }; test("sorts by file, location, code, category, source, and text without mutating input", () => { - const firstFile = { ...diagnostic, fileName: toRootedFilePath("/A.ts", undefined), pos: 0, end: 1 }; + const firstFile = { ...diagnostic, fileName: toRootedFilePath("/A.ts", /*currentDirectory*/ undefined), pos: 0, end: 1 }; const expected = [ diagnostic, firstFile, @@ -36,7 +36,7 @@ describe("sortAndDeduplicateDiagnostics", () => { { ...firstFile, code: 2 }, { ...firstFile, end: 2 }, { ...firstFile, pos: 1, end: 2 }, - { ...firstFile, fileName: toRootedFilePath("/a.ts", undefined) }, + { ...firstFile, fileName: toRootedFilePath("/a.ts", /*currentDirectory*/ undefined) }, ].map((item, index) => ({ ...item, index })); const input = Object.freeze([...expected].reverse()); for (const sort of [sortAndDeduplicateDiagnostics, sortAndDeduplicateDiagnosticsSync]) { diff --git a/packages/typescript/test/encoder.test.ts b/packages/typescript/test/encoder.test.ts index 395024ab9a96d..3aada56482d51 100644 --- a/packages/typescript/test/encoder.test.ts +++ b/packages/typescript/test/encoder.test.ts @@ -60,7 +60,7 @@ const concurrency = areTestsFiltered(); function makeSF(text: string, fileName: string, statements: readonly Statement[]): SourceFile { const endOfFileToken = createToken(SyntaxKind.EndOfFile); - const rootedFilePath = toRootedFilePath(fileName, undefined); + const rootedFilePath = toRootedFilePath(fileName, /*currentDirectory*/ undefined); return createSourceFile( statements, endOfFileToken, @@ -80,7 +80,7 @@ describe("Encoder", { concurrency }, () => { const sf = makeSF("", "/test.ts", [statement]); const decoded = decode(encodeSourceFile(sf)); - for (const range of [decoded, decoded.statements!, decoded.statements!.at(0)!, decoded.endOfFileToken!]) { + for (const range of [decoded, decoded.statements!, decoded.statements!.at(0), decoded.endOfFileToken!]) { assert.strictEqual(range.pos, -1); assert.strictEqual(range.end, -1); } @@ -99,7 +99,7 @@ describe("Encoder", { concurrency }, () => { // Verify header const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength); - const metadata = view.getUint32(0, true); + const metadata = view.getUint32(0, /*littleEndian*/ true); assert.strictEqual(metadata >>> 24, PROTOCOL_VERSION); assert.strictEqual(HEADER_SIZE, 64); @@ -109,18 +109,18 @@ describe("Encoder", { concurrency }, () => { assert.strictEqual(decoded.fileName, "/test.ts"); assert.strictEqual(decoded.path, "/test.ts"); assert.strictEqual(decoded.text, ""); - assert.strictEqual(decoded.contentMapper, undefined); - assert.strictEqual(decoded.virtualFileName, undefined); - assert.strictEqual(decoded.diagnosticDirectives, undefined); - assert.strictEqual(decoded.supplementalSourceFileNames, undefined); - assert.strictEqual(decoded.canonicalSourceFileName, undefined); + assert.strictEqual(decoded.contentMapper, /*expected*/ undefined); + assert.strictEqual(decoded.virtualFileName, /*expected*/ undefined); + assert.strictEqual(decoded.diagnosticDirectives, /*expected*/ undefined); + assert.strictEqual(decoded.supplementalSourceFileNames, /*expected*/ undefined); + assert.strictEqual(decoded.canonicalSourceFileName, /*expected*/ undefined); }); test("keeps adjacent surrogate string-table entries separate", () => { const high = String.fromCharCode(0xD800); const low = String.fromCharCode(0xDC00); - const fileName = toRootedFilePath(`/${high}`, undefined); - const path = pathKey(toRootedFilePath(`/${low}`, undefined), CaseSensitivity.Sensitive); + const fileName = toRootedFilePath(`/${high}`, /*currentDirectory*/ undefined); + const path = pathKey(toRootedFilePath(`/${low}`, /*currentDirectory*/ undefined), CaseSensitivity.Sensitive); const sf = createSourceFile([], createToken(SyntaxKind.EndOfFile), "", fileName, path); const decoded = decode(encodeSourceFile(sf)); @@ -130,9 +130,9 @@ describe("Encoder", { concurrency }, () => { test("encodes source file with identifier", () => { const id = createIdentifier("hello"); - const decl = createVariableDeclaration(id, undefined, undefined, undefined); + const decl = createVariableDeclaration(id, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); const declList = createVariableDeclarationList([decl], 0); - const stmt = createVariableStatement(undefined, declList); + const stmt = createVariableStatement(/*modifiers*/ undefined, declList); const sf = makeSF("var hello = 42;", "/test.ts", [stmt]); const encoded = encodeSourceFile(sf); @@ -145,14 +145,14 @@ describe("Encoder", { concurrency }, () => { const stmts = decoded.statements; assert.ok(stmts); assert.strictEqual(stmts.length, 1); - const decodedStmt = stmts.at(0)!; + const decodedStmt = stmts.at(0); assert.strictEqual(decodedStmt.kind, SyntaxKind.VariableStatement); }); test("encodes if statement with optional else", () => { const condition = createIdentifier("ok"); const thenBlock = createBlock([]); - const ifStmt = createIfStatement(condition, thenBlock, undefined); + const ifStmt = createIfStatement(condition, thenBlock, /*elseStatement*/ undefined); const sf = makeSF("if (ok) {}", "/test.ts", [ifStmt]); const encoded = encodeSourceFile(sf); @@ -160,7 +160,7 @@ describe("Encoder", { concurrency }, () => { const stmts = decoded.statements; assert.ok(stmts); assert.strictEqual(stmts.length, 1); - const decodedIf = stmts.at(0)!; + const decodedIf = stmts.at(0); assert.strictEqual(decodedIf.kind, SyntaxKind.IfStatement); assert.ok(decodedIf.expression); assert.strictEqual(decodedIf.expression.kind, SyntaxKind.Identifier); @@ -168,7 +168,7 @@ describe("Encoder", { concurrency }, () => { assert.ok(decodedIf.thenStatement); assert.strictEqual(decodedIf.thenStatement.kind, SyntaxKind.Block); // No else - assert.strictEqual(decodedIf.elseStatement, undefined); + assert.strictEqual(decodedIf.elseStatement, /*expected*/ undefined); }); test("encodes if statement with else", () => { @@ -182,7 +182,7 @@ describe("Encoder", { concurrency }, () => { const decoded = decode(encoded); const stmts = decoded.statements; assert.ok(stmts); - const decodedIf = stmts.at(0)!; + const decodedIf = stmts.at(0); assert.strictEqual(decodedIf.kind, SyntaxKind.IfStatement); assert.ok(decodedIf.expression); assert.ok(decodedIf.thenStatement); @@ -193,7 +193,7 @@ describe("Encoder", { concurrency }, () => { test("encodes function declaration", () => { const name = createIdentifier("foo"); const body = createBlock([]); - const fn = createFunctionDeclaration(undefined, undefined, name, undefined, [], undefined, body); + const fn = createFunctionDeclaration(/*modifiers*/ undefined, /*asteriskToken*/ undefined, name, /*typeParameters*/ undefined, [], /*type*/ undefined, body); const sf = makeSF("function foo() {}", "/test.ts", [fn]); const encoded = encodeSourceFile(sf); @@ -201,7 +201,7 @@ describe("Encoder", { concurrency }, () => { const stmts = decoded.statements; assert.ok(stmts); assert.strictEqual(stmts.length, 1); - const decodedFn = stmts.at(0)!; + const decodedFn = stmts.at(0); assert.strictEqual(decodedFn.kind, SyntaxKind.FunctionDeclaration); assert.ok(decodedFn.name); assert.strictEqual(decodedFn.name.kind, SyntaxKind.Identifier); @@ -213,15 +213,15 @@ describe("Encoder", { concurrency }, () => { test("encodes arbitrary node (not source file)", () => { const condition = createIdentifier("x"); const thenBlock = createBlock([]); - const ifStmt = createIfStatement(condition, thenBlock, undefined); + const ifStmt = createIfStatement(condition, thenBlock, /*elseStatement*/ undefined); const encoded = encodeNode(ifStmt); assert.ok(encoded instanceof Uint8Array); // Root node at index 1 should be IfStatement const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength); - const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, true); - const rootKind = view.getUint32(offsetNodes + NODE_LEN, true); + const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, /*littleEndian*/ true); + const rootKind = view.getUint32(offsetNodes + NODE_LEN, /*littleEndian*/ true); assert.strictEqual(rootKind, SyntaxKind.IfStatement); }); @@ -229,7 +229,7 @@ describe("Encoder", { concurrency }, () => { const sf = makeSF("", "/test.ts", []); const encoded = encodeSourceFile(sf); const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength); - assert.strictEqual(view.getUint32(0, true) >>> 24, PROTOCOL_VERSION); + assert.strictEqual(view.getUint32(0, /*littleEndian*/ true) >>> 24, PROTOCOL_VERSION); }); test("encodes source files without content mapping metadata", () => { @@ -243,11 +243,11 @@ describe("Encoder", { concurrency }, () => { test("boolean properties are encoded", () => { // Block with multiLine=true - const block = createBlock([], true); + const block = createBlock([], /*multiLine*/ true); const encoded = encodeNode(block); const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength); - const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, true); - const data = view.getUint32(offsetNodes + NODE_LEN + NODE_OFFSET_DATA, true); + const offsetNodes = view.getUint32(HEADER_OFFSET_NODES, /*littleEndian*/ true); + const data = view.getUint32(offsetNodes + NODE_LEN + NODE_OFFSET_DATA, /*littleEndian*/ true); // Bit 24 should be 1 (multiLine) assert.strictEqual((data >>> 24) & 1, 1); }); @@ -262,7 +262,7 @@ describe("Encoder", { concurrency }, () => { const decoded = decode(encoded); const stmts = decoded.statements; assert.ok(stmts); - const decodedStmt = stmts.at(0)!; + const decodedStmt = stmts.at(0); assert.strictEqual(decodedStmt.kind, SyntaxKind.ExpressionStatement); const expr = decodedStmt.expression!; assert.strictEqual(expr.kind, SyntaxKind.PostfixUnaryExpression); @@ -281,7 +281,7 @@ describe("Encoder", { concurrency }, () => { const decoded = decode(encoded); const stmts = decoded.statements; assert.ok(stmts); - const expr = stmts.at(0)!.expression!; + const expr = stmts.at(0).expression!; assert.strictEqual(expr.kind, SyntaxKind.PrefixUnaryExpression); assert.strictEqual(expr.operator, SyntaxKind.ExclamationToken); }); @@ -294,7 +294,7 @@ describe("Encoder", { concurrency }, () => { const encoded = encodeSourceFile(sf); const decoded = decode(encoded); - const expr = decoded.statements!.at(0)!.expression!; + const expr = decoded.statements!.at(0).expression!; assert.strictEqual(expr.kind, SyntaxKind.PostfixUnaryExpression); assert.strictEqual(expr.operator, SyntaxKind.MinusMinusToken); }); @@ -306,12 +306,12 @@ describe("Encoder", { concurrency }, () => { // must return undefined, not throw "Expected only one child". const tagName = createIdentifier("div"); const emptyAttrs = createJsxAttributes([]); - const opening = createJsxOpeningElement(tagName, undefined, emptyAttrs); + const opening = createJsxOpeningElement(tagName, /*typeArguments*/ undefined, emptyAttrs); const closing = createJsxClosingElement(createIdentifier("div")); const jsx = createJsxElement(opening, [], closing); const stmt = createVariableStatement( - undefined, - createVariableDeclarationList([createVariableDeclaration(createIdentifier("x"), undefined, undefined, jsx)], 0), + /*modifiers*/ undefined, + createVariableDeclarationList([createVariableDeclaration(createIdentifier("x"), /*exclamationToken*/ undefined, /*type*/ undefined, jsx)], 0), ); const sf = makeSF("const x =
;", "/test.tsx", [stmt]); @@ -319,11 +319,11 @@ describe("Encoder", { concurrency }, () => { const decoded = decode(encoded); // Walk to JsxOpeningElement → attributes (JsxAttributes) - const varStmt = decoded.statements!.at(0)!; + const varStmt = decoded.statements!.at(0); const declList = varStmt.declarationList!; const declarationsNode = declList.declarations!; assert.ok(declarationsNode instanceof RemoteNodeList); - const varDecl = declarationsNode.at(0)!; + const varDecl = declarationsNode.at(0); const jsxElem = varDecl.initializer!; assert.strictEqual(jsxElem.kind, SyntaxKind.JsxElement); const openingElem = jsxElem.openingElement!; @@ -331,7 +331,7 @@ describe("Encoder", { concurrency }, () => { const attrs = openingElem.attributes! as RemoteNode; assert.strictEqual(attrs.kind, SyntaxKind.JsxAttributes); // Empty properties should return undefined, not throw - assert.strictEqual(jsxElem.typeArguments, undefined); + assert.strictEqual(jsxElem.typeArguments, /*expected*/ undefined); }); test("NodeList element access is consistent across forward, backward, and random order", () => { @@ -349,36 +349,36 @@ describe("Encoder", { concurrency }, () => { const sf = makeSF(text, "/test.ts", [stmt]); const decoded = decode(encodeSourceFile(sf)); - const arrayExpr = (decoded.statements!.at(0)! as RemoteNode).expression! as RemoteNode; - const list = arrayExpr.elements! as unknown as RemoteNodeList; + const arrayExpr = decoded.statements!.at(0).expression!; + const list = arrayExpr.elements!; assert.strictEqual(list.length, count); // Independent decode used as an oracle: fresh cursor per lookup. const posOf = (i: number) => { - const freshExpr = (decode(encodeSourceFile(sf)).statements!.at(0)! as RemoteNode).expression! as RemoteNode; - return (freshExpr.elements! as unknown as RemoteNodeList).at(i)!.pos; + const freshExpr = decode(encodeSourceFile(sf)).statements!.at(0).expression!; + return freshExpr.elements!.at(i).pos; }; const expected = Array.from({ length: count }, (_, i) => posOf(i)); // Forward sequential (exercises cursor resume). for (let i = 0; i < count; i++) { - assert.strictEqual(list.at(i)!.pos, expected[i], `forward at(${i})`); + assert.strictEqual(list.at(i).pos, expected[i], `forward at(${i})`); } // Backward sequential (cursor must reset when index < cursor). for (let i = count - 1; i >= 0; i--) { - assert.strictEqual(list.at(i)!.pos, expected[i], `backward at(${i})`); + assert.strictEqual(list.at(i).pos, expected[i], `backward at(${i})`); } // Random order, with repeats. for (const i of [3, 7, 1, 7, 0, 9, 4, 4, 2, 8, 5, 6, 0, 9]) { - assert.strictEqual(list.at(i)!.pos, expected[i], `random at(${i})`); + assert.strictEqual(list.at(i).pos, expected[i], `random at(${i})`); } // Negative indices. - assert.strictEqual(list.at(-1)!.pos, expected[count - 1], "at(-1)"); - assert.strictEqual(list.at(-count)!.pos, expected[0], `at(-${count})`); + assert.strictEqual(list.at(-1).pos, expected[count - 1], "at(-1)"); + assert.strictEqual(list.at(-count).pos, expected[0], `at(-${count})`); // Indexed getters (0..15) and spread must agree with at(). - assert.strictEqual((list[0] as RemoteNode).pos, expected[0]); - assert.strictEqual((list[9] as RemoteNode).pos, expected[9]); + assert.strictEqual(list[0].pos, expected[0]); + assert.strictEqual(list[9].pos, expected[9]); assert.deepStrictEqual([...list].map(n => n.pos), expected); }); }); diff --git a/packages/typescript/test/nodelist.bench.ts b/packages/typescript/test/nodelist.bench.ts index a27b42bc1c455..5e5ef08e4b5ad 100644 --- a/packages/typescript/test/nodelist.bench.ts +++ b/packages/typescript/test/nodelist.bench.ts @@ -56,7 +56,7 @@ function makeSourceFileWithLargeList(elementCount: number): Uint8Array { const array = createArrayLiteralExpression(elements); const stmt: Statement = createExpressionStatement(array); const eof = createToken(SyntaxKind.EndOfFile); - const fileName = toRootedFilePath("/bench.ts", undefined); + const fileName = toRootedFilePath("/bench.ts", /*currentDirectory*/ undefined); const sf: SourceFile = createSourceFile( [stmt], eof, @@ -100,6 +100,7 @@ export function runBenchmarks(options?: { filter?: string; size?: string; }): vo .add("index access (list[i])", () => { const list = getElementsList(encoded); let sum = 0; + // eslint-disable-next-line @typescript-eslint/prefer-for-of -- Benchmark indexed access. for (let i = 0; i < list.length; i++) { sum += list[i].pos; } @@ -109,7 +110,7 @@ export function runBenchmarks(options?: { filter?: string; size?: string; }): vo const list = getElementsList(encoded); let sum = 0; for (let i = 0; i < list.length; i++) { - sum += list.at(i)!.pos; + sum += list.at(i).pos; } if (sum < 0) throw new Error("unreachable"); }) diff --git a/packages/typescript/test/path.test.ts b/packages/typescript/test/path.test.ts index cb99f1a662080..4dca7319676be 100644 --- a/packages/typescript/test/path.test.ts +++ b/packages/typescript/test/path.test.ts @@ -43,11 +43,11 @@ type _PathKeyIsNotRootedFilePath = AssertFalse>; test("path keys are constructed from rooted paths", () => { - const workspace = toRootedDirectoryPath("/workspace", undefined); + const workspace = toRootedDirectoryPath("/workspace", /*currentDirectory*/ undefined); assert.strictEqual(pathKey(toRootedPath("src/file.ts", workspace), CaseSensitivity.Sensitive), "/workspace/src/file.ts"); assert.strictEqual(pathKey(toRootedPath("SRC/file.ts", workspace), CaseSensitivity.Insensitive), "/workspace/src/file.ts"); - assert.strictEqual(pathKey(toRootedPath("^/untitled/file.ts", undefined), CaseSensitivity.Sensitive), "^/untitled/file.ts"); - assert.throws(() => toRootedPath("src/file.ts", undefined), /Path is not rooted/); + assert.strictEqual(pathKey(toRootedPath("^/untitled/file.ts", /*currentDirectory*/ undefined), CaseSensitivity.Sensitive), "^/untitled/file.ts"); + assert.throws(() => toRootedPath("src/file.ts", /*currentDirectory*/ undefined), /Path is not rooted/); const upperDynamic = tryRootedPathFromNormalized(documentURIToFileName("custom:~ts-uri-escape~Foo.ts")); const lowerDynamic = tryRootedPathFromNormalized(documentURIToFileName("custom:~ts-uri-escape~foo.ts")); assert.ok(upperDynamic); @@ -90,14 +90,14 @@ test("tryRootedPathFromNormalized validates without transforming", () => { "file://server", ] ) { - assert.strictEqual(tryRootedPathFromNormalized(path), undefined); + assert.strictEqual(tryRootedPathFromNormalized(path), /*expected*/ undefined); } }); test("local file URL roots are identified case-insensitively", () => { - assert.strictEqual(toRootedPath("FILE:///C:/../x.ts", undefined), "FILE:///C:/x.ts"); + assert.strictEqual(toRootedPath("FILE:///C:/../x.ts", /*currentDirectory*/ undefined), "FILE:///C:/x.ts"); assert.strictEqual( - toRootedPath("file://LOCALHOST/C%3A/../x.ts", undefined), + toRootedPath("file://LOCALHOST/C%3A/../x.ts", /*currentDirectory*/ undefined), "file://LOCALHOST/C%3A/x.ts", ); }); @@ -163,12 +163,12 @@ test("non-file URIs round-trip through normalized file names", () => { "custom:~ts-uri-escape~file.ts", ] ) { - assert.strictEqual(documentURIToFileName(uri).endsWith(".ts"), true); + assert.strictEqual(documentURIToFileName(uri).endsWith(".ts"), /*expected*/ true); } for (const extension of [".d.ts", ".d.mts", ".d.css.ts"]) { assert.strictEqual( documentURIToFileName("custom:~ts-uri-escape~types" + extension).endsWith(extension), - true, + /*expected*/ true, ); } @@ -179,7 +179,7 @@ test("non-file URIs round-trip through normalized file names", () => { ordinarySibling.substring(0, ordinarySibling.lastIndexOf("/")), ); const queryFile = documentURIToFileName("custom:path/file.ts?rev=a/b"); - assert.strictEqual(queryFile.endsWith(".ts"), true); + assert.strictEqual(queryFile.endsWith(".ts"), /*expected*/ true); assert.strictEqual( queryFile.substring(0, queryFile.lastIndexOf("/")), documentURIToFileName("custom:path/other.ts").substring( @@ -207,14 +207,14 @@ test("CaseSensitivity exposes explicit checks", () => { assert.strictEqual(canonicalize("/repo/\u0130project/file.ts", CaseSensitivity.Insensitive), "/repo/\u0130project/file.ts"); assert.strictEqual(canonicalize("/repo/\u212A/file.ts", CaseSensitivity.Insensitive), "/repo/k/file.ts"); assert.strictEqual(canonicalize("/repo/\u039F\u03A3.ts", CaseSensitivity.Insensitive), "/repo/\u03BF\u03C3.ts"); - assert.strictEqual(isCaseSensitive(CaseSensitivity.Sensitive), true); - assert.strictEqual(isCaseSensitive(CaseSensitivity.Insensitive), false); - assert.strictEqual(isCaseInsensitive(CaseSensitivity.Insensitive), true); - assert.strictEqual(isCaseInsensitive(CaseSensitivity.Sensitive), false); + assert.strictEqual(isCaseSensitive(CaseSensitivity.Sensitive), /*expected*/ true); + assert.strictEqual(isCaseSensitive(CaseSensitivity.Insensitive), /*expected*/ false); + assert.strictEqual(isCaseInsensitive(CaseSensitivity.Insensitive), /*expected*/ true); + assert.strictEqual(isCaseInsensitive(CaseSensitivity.Sensitive), /*expected*/ false); }); test("rooted path constructors enforce the type lattice", () => { - const workspace = toRootedDirectoryPath("/workspace", undefined); + const workspace = toRootedDirectoryPath("/workspace", /*currentDirectory*/ undefined); const rootedPath = toRootedPath("src/file.ts", workspace); const filePath = toRootedFilePath("src/file.ts", workspace); const directoryPath = toRootedDirectoryPath("src", workspace); @@ -225,12 +225,12 @@ test("rooted path constructors enforce the type lattice", () => { assert.strictEqual(rootedFilePathFromPath(rootedPath), rootedPath); assert.strictEqual(rootedDirectoryPathFromPath(rootedPath), rootedPath); assert.strictEqual(pathKey(filePath, CaseSensitivity.Sensitive), filePath); - assert.strictEqual(toRootedFilePath("^/untitled/file.ts", undefined), "^/untitled/file.ts"); + assert.strictEqual(toRootedFilePath("^/untitled/file.ts", /*currentDirectory*/ undefined), "^/untitled/file.ts"); assert.strictEqual(toRootedFilePath("^/untitled/file.ts", workspace), "^/untitled/file.ts"); assert.throws(() => toRootedPath("", workspace), /must not be empty/); assert.throws(() => toRootedFilePath("", workspace), /must not be empty/); assert.throws(() => toRootedDirectoryPath("", workspace), /must not be empty/); - assert.throws(() => toRootedFilePath("src/file.ts", undefined), /Path is not rooted/); + assert.throws(() => toRootedFilePath("src/file.ts", /*currentDirectory*/ undefined), /Path is not rooted/); for ( const [input, expected] of [ ["c:", "c:/"], @@ -240,10 +240,10 @@ test("rooted path constructors enforce the type lattice", () => { ["^/~ts-uri~/custom/authority?query", "^/~ts-uri~/custom/authority?query/"], ] as const ) { - assert.strictEqual(toRootedPath(input, undefined), expected); - assert.strictEqual(toRootedFilePath(input, undefined), expected); - assert.strictEqual(toRootedDirectoryPath(input, undefined), expected); - assert.strictEqual(tryRootedPathFromNormalized(input), undefined); + assert.strictEqual(toRootedPath(input, /*currentDirectory*/ undefined), expected); + assert.strictEqual(toRootedFilePath(input, /*currentDirectory*/ undefined), expected); + assert.strictEqual(toRootedDirectoryPath(input, /*currentDirectory*/ undefined), expected); + assert.strictEqual(tryRootedPathFromNormalized(input), /*expected*/ undefined); assert.strictEqual(tryRootedPathFromNormalized(expected), expected); } for ( @@ -254,13 +254,13 @@ test("rooted path constructors enforce the type lattice", () => { "http://server/?query/", ] ) { - assert.throws(() => toRootedPath(input, undefined), /must not contain a URL query or fragment/); - assert.strictEqual(tryRootedPathFromNormalized(input), undefined); + assert.throws(() => toRootedPath(input, /*currentDirectory*/ undefined), /must not contain a URL query or fragment/); + assert.strictEqual(tryRootedPathFromNormalized(input), /*expected*/ undefined); } - const diskWithSchemeText = toRootedPath("/a://b?x/../y", undefined); + const diskWithSchemeText = toRootedPath("/a://b?x/../y", /*currentDirectory*/ undefined); assert.strictEqual(diskWithSchemeText, "/a:/y"); assert.strictEqual(tryRootedPathFromNormalized(diskWithSchemeText), diskWithSchemeText); - const urlDirectory = toRootedDirectoryPath("http://server/base", undefined); + const urlDirectory = toRootedDirectoryPath("http://server/base", /*currentDirectory*/ undefined); assert.throws(() => toRootedPath("file.ts?query", urlDirectory), /query or fragment|Path is not rooted/); assert.throws(() => toRootedPath("file.ts?query/..", urlDirectory), /must not contain a query or fragment/); }); @@ -300,14 +300,14 @@ test("parseNodeHandleFromCompiler validates serialized fields", () => { test("tryPathKeyFromCanonical preserves producer canonicalization", () => { assert.strictEqual(tryPathKeyFromCanonical("/Workspace/src/File.ts"), "/Workspace/src/File.ts"); - assert.strictEqual(tryPathKeyFromCanonical("/workspace/../src/file.ts"), undefined); + assert.strictEqual(tryPathKeyFromCanonical("/workspace/../src/file.ts"), /*expected*/ undefined); }); test("createVirtualFileSystem normalizes raw input keys once", () => { const fs = createVirtualFileSystem({ "/workspace/src/../file.ts": "content", }); - assert.strictEqual(fs.readFile(toRootedFilePath("/workspace/file.ts", undefined)), "content"); + assert.strictEqual(fs.readFile(toRootedFilePath("/workspace/file.ts", /*currentDirectory*/ undefined)), "content"); assert.throws(() => createVirtualFileSystem({ "workspace/file.ts": "content" }), /Path is not rooted/); }); @@ -316,16 +316,16 @@ test("createVirtualFileSystem supports object prototype path components", () => "/toString/file.ts": "toString", "/__proto__/constructor.ts": "constructor", }); - assert.strictEqual(fs.readFile(toRootedFilePath("/toString/file.ts", undefined)), "toString"); - assert.strictEqual(fs.readFile(toRootedFilePath("/__proto__/constructor.ts", undefined)), "constructor"); + assert.strictEqual(fs.readFile(toRootedFilePath("/toString/file.ts", /*currentDirectory*/ undefined)), "toString"); + assert.strictEqual(fs.readFile(toRootedFilePath("/__proto__/constructor.ts", /*currentDirectory*/ undefined)), "constructor"); }); test("createVirtualFileSystem respects case sensitivity", () => { const fs = createVirtualFileSystem({ "/Workspace/Foo.ts": "content", }, { caseSensitivity: CaseSensitivity.Insensitive }); - assert.strictEqual(fs.readFile(toRootedFilePath("/workspace/foo.ts", undefined)), "content"); - assert.deepStrictEqual(fs.getAccessibleEntries(toRootedDirectoryPath("/workspace", undefined)), { + assert.strictEqual(fs.readFile(toRootedFilePath("/workspace/foo.ts", /*currentDirectory*/ undefined)), "content"); + assert.deepStrictEqual(fs.getAccessibleEntries(toRootedDirectoryPath("/workspace", /*currentDirectory*/ undefined)), { files: ["Foo.ts"], directories: [], symlinks: undefined, diff --git a/packages/typescript/test/proto.test.ts b/packages/typescript/test/proto.test.ts index 17a1d063cfae9..bc79b07db56c6 100644 --- a/packages/typescript/test/proto.test.ts +++ b/packages/typescript/test/proto.test.ts @@ -1,21 +1,51 @@ import assert from "node:assert"; import test from "node:test"; import { SymbolOwnerKind } from "../enums/symbolOwnerKind.js"; +import { encodeFileSystemCallbackResult } from "../src/api/fsCallbacks.ts"; import type { SymbolOwner as ProtocolSymbolOwner, SymbolResponse as ProtocolSymbolResponse, } from "../src/api/proto.generated.ts"; import { + resolveFileName, validateSymbolOwner, validateSymbolResponse, } from "../src/api/proto.ts"; -import type { ProjectId } from "../src/api/proto.ts"; +import type { + DocumentIdentifier, + ProjectId, +} from "../src/api/proto.ts"; import { SourceFileCache } from "../src/api/sourceFileCache.ts"; import type { PathKey, RootedFilePath, } from "../src/ast/index.ts"; +test("document identifier validation rejects nullish and malformed values", () => { + const invalidIdentifiers: [unknown, string][] = [ + [JSON.parse("null"), "null"], + [undefined, "undefined"], + [0, "0"], + [{ uri: undefined }, "an object with keys: uri"], + ]; + for (const [identifier, received] of invalidIdentifiers) { + assert.throws(() => resolveFileName(identifier as DocumentIdentifier), { + name: "TypeError", + message: `Expected a string or { uri } for the document, received ${received}`, + }); + } +}); + +test("filesystem callback results reject nullish and other invalid entries", () => { + const invalidResults: unknown[] = [JSON.parse("null"), undefined, false, 0]; + for (const result of invalidResults) { + assert.throws(() => encodeFileSystemCallbackResult("getAccessibleEntries", result), { + name: "TypeError", + message: "Invalid result from filesystem callback 'getAccessibleEntries'", + }); + } +}); + test("symbol ownership protocol validation rejects mixed variants", () => { const project = 1; const file = { @@ -47,10 +77,10 @@ test("symbol ownership protocol validation rejects mixed variants", () => { { kind: 99 }, ] as ProtocolSymbolOwner[] ) { - assert.throws(() => validateSymbolOwner(owner), /Invalid .*symbol owner|Invalid symbol owner kind/); + assert.throws(() => validateSymbolOwner(owner), /Invalid .*symbol owner/); } assert.throws( - () => validateSymbolResponse({ ...response, reference: { kind: SymbolOwnerKind.Snapshot, id: 1, file } as ProtocolSymbolResponse["reference"] }), + () => validateSymbolResponse({ ...response, reference: { kind: SymbolOwnerKind.Snapshot, id: 1, file } }), /Invalid snapshot symbol owner/, ); }); @@ -66,13 +96,13 @@ test("source file cache resolves references without creating records", () => { scriptKind: 3, nodeId: "7", }; - assert.strictEqual(cache.findRecord("7"), undefined); + assert.strictEqual(cache.findRecord("7"), /*expected*/ undefined); assert.equal(cache.size, 0); const record = cache.getOrCreateRecord(file, 1, project); assert.strictEqual(cache.findRecord("7"), record); cache.releaseSnapshot(1); - assert.strictEqual(cache.findRecord("7"), undefined); + assert.strictEqual(cache.findRecord("7"), /*expected*/ undefined); }); test("source file cache transfers record ownership between snapshots", () => { @@ -98,6 +128,6 @@ test("source file cache transfers record ownership between snapshots", () => { // The record is evicted once its final snapshot owner is released, and a // stale wrapper cannot resurrect the evicted record. cache.releaseSnapshot(2); - assert.strictEqual(cache.findRecord("7"), undefined); + assert.strictEqual(cache.findRecord("7"), /*expected*/ undefined); assert.throws(() => cache.retainRecord(record, 3, project), /is no longer cached/); }); diff --git a/packages/typescript/test/sync/api-generators.test.ts b/packages/typescript/test/sync/api-generators.test.ts index 63cb8f53518f6..2f248d02a49ef 100644 --- a/packages/typescript/test/sync/api-generators.test.ts +++ b/packages/typescript/test/sync/api-generators.test.ts @@ -206,7 +206,7 @@ function parityCase( return { ownerName, methodName, - runGenerator: function* () { + *runGenerator() { generatedResult = { value: yield* method.gen(...args) }; }, assertEquivalent: message => { @@ -434,7 +434,7 @@ function observeRequestBatches( context: TestContext, ): void { // @ts-ignore -- Internal client transport is exercised by source tests. - const client = api["client"]; + const client = api.client; const batchRequests = client.batchRequests.bind(client); context.mock.method(client, "batchRequests", (requests: readonly APIRequest[]) => { requestBatches.push(requests.map(request => request.method)); @@ -519,6 +519,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("all and defer yield discriminated host messages without starting children", () => { let started = false; + // eslint-disable-next-line require-yield -- This child must never start. function* child() { started = true; return "child"; @@ -530,6 +531,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const generators: APIRequestGenerator[] = [all(joined), defer(deferred)]; for (const generator of generators) { const state = generator.next(); + // eslint-disable-next-line local/no-in-operator -- Narrow the host message union. if (state.done || !("method" in state.value)) assert.fail("Expected a host message"); switch (state.value.method) { case "__all": @@ -549,6 +551,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("all preserves generator protocol behavior", () => { let started = false; + // eslint-disable-next-line require-yield -- This child must never start. function* child() { started = true; return "child"; @@ -580,6 +583,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("defer preserves generator protocol behavior", () => { let started = false; + // eslint-disable-next-line require-yield -- This child must never start. function* child() { started = true; return "child"; @@ -600,11 +604,12 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => thrown.next(); disposed.next(); } - assert.deepEqual(returned.return(undefined), { done: true, value: undefined }); + assert.deepEqual(returned.return(/*value*/ undefined), { done: true, value: undefined }); assert.deepEqual(returned.next(), { done: true, value: undefined }); const error = new Error("failed"); assert.throws(() => thrown.throw(error), actual => actual === error); assert.deepEqual(thrown.next(), { done: true, value: undefined }); + // eslint-disable-next-line local/no-in-operator -- Narrow the iterator with its inherited disposal method. assert.ok(globalThis.Symbol.dispose in disposed); const dispose = disposed[globalThis.Symbol.dispose]; assert.ok(typeof dispose === "function"); @@ -617,7 +622,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("rejects deferred generator reuse after completion", () => { let completed = false; function* child(): Generator { - const result = yield { method: "request", params: null } as unknown as APIRequest; + const result = yield { method: "request", params: undefined } as unknown as APIRequest; completed = true; return result; } @@ -630,12 +635,13 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("joins nested, empty, and synchronously completed groups in result order", () => { + // eslint-disable-next-line require-yield -- Exercise synchronous completion. function* completed(value: string) { return value; } function* request(value: string, rounds: number): Generator { for (let round = 0; round < rounds; round++) { - yield { method: value, params: null } as unknown as APIRequest; + yield { method: value, params: undefined } as unknown as APIRequest; } return value; } @@ -652,9 +658,11 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("preserves tuple results through all and any generator types", () => { + // eslint-disable-next-line require-yield -- Exercise synchronous completion. function* numberResult() { return 42; } + // eslint-disable-next-line require-yield -- Exercise synchronous completion. function* stringResult() { return "result"; } @@ -678,7 +686,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("preserves sibling order across repeated nested joins", () => { function* request(method: string): Generator { - return yield { method, params: null } as unknown as APIRequest; + return yield { method, params: undefined } as unknown as APIRequest; } function* foreground() { for (let round = 0; round < 3; round++) { @@ -702,7 +710,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const events: string[] = []; const batches: string[][] = []; function* request(method: string): Generator { - const result = yield { method, params: null } as unknown as APIRequest; + const result = yield { method, params: undefined } as unknown as APIRequest; events.push(method); return result; } @@ -749,7 +757,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("preserves singleton join continuations through requests, errors, and deferred work", () => { const events: string[] = []; function* request(method: string): Generator { - return yield { method, params: null } as unknown as APIRequest; + return yield { method, params: undefined } as unknown as APIRequest; } function* recovering() { try { @@ -785,7 +793,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("finishes joined foreground cleanup before deferred request errors", () => { const events: string[] = []; function* request(method: string): Generator { - yield { method, params: null } as unknown as APIRequest; + yield { method, params: undefined } as unknown as APIRequest; } function* foreground() { try { @@ -805,22 +813,21 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("completes root all helpers before detached work finishes", () => { - let joined: AllAPIRequestGenerator<[string]>; function* foreground(): Generator { - return yield { method: "foreground", params: null } as unknown as APIRequest; + return yield { method: "foreground", params: undefined } as unknown as APIRequest; } function* background(): Generator { - yield { method: "background", params: null } as unknown as APIRequest; + yield { method: "background", params: undefined } as unknown as APIRequest; assert.deepEqual(joined.next(["unexpected"]), { done: true, value: undefined }); } - joined = all(foreground(), defer(background())); + const joined: AllAPIRequestGenerator<[string]> = all(foreground(), defer(background())); assert.deepEqual(executeRequestGenerators([joined], requests => requests.map(request => ({ result: request.method }))), [["foreground"]]); }); test("throws nested all failures into the waiting parent", () => { const events: string[] = []; function* failing(): Generator { - yield { method: "bad", params: null } as unknown as APIRequest; + yield { method: "bad", params: undefined } as unknown as APIRequest; } function* parent() { try { @@ -839,7 +846,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("cancels failed join siblings but finishes detached and unrelated work", () => { const events: string[] = []; function* request(method: string): Generator { - const result = yield { method, params: null } as unknown as APIRequest; + const result = yield { method, params: undefined } as unknown as APIRequest; events.push(method); return result; } @@ -859,7 +866,9 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("catches synchronous join failures including undefined", () => { + // eslint-disable-next-line require-yield -- Exercise synchronous failure. function* failing(): APIRequestGenerator { + // eslint-disable-next-line no-throw-literal -- Exercise propagation of an undefined error. throw undefined; } function* parent() { @@ -867,7 +876,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => yield* all(all(failing())); } catch (error) { - assert.strictEqual(error, undefined); + assert.strictEqual(error, /*expected*/ undefined); return "recovered"; } return "unexpected"; @@ -877,6 +886,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("does not route synchronous deferred failures through a waiting join", () => { const events: string[] = []; + // eslint-disable-next-line require-yield -- Exercise synchronous failure. function* failing(): APIRequestGenerator { throw new Error("deferred failure"); } @@ -897,7 +907,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("rejects generator reuse across joins and deferred work", () => { function* request(): Generator { - return yield { method: "request", params: null } as unknown as APIRequest; + return yield { method: "request", params: undefined } as unknown as APIRequest; } for (const wrap of [all, defer]) { const generator = request(); @@ -910,7 +920,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("rejects completed generator reuse after a join finishes", () => { function* request(): Generator { - return yield { method: "request", params: null } as unknown as APIRequest; + return yield { method: "request", params: undefined } as unknown as APIRequest; } for (const wrap of [all, defer]) { const generator = request(); @@ -944,6 +954,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("deduplicates initialization across nested joins", () => { function* request(method: string): Generator { + // eslint-disable-next-line no-restricted-syntax -- Initialize requests require null parameters. return yield { method, params: null } as unknown as APIRequest; } const batches: string[][] = []; @@ -994,7 +1005,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const events: string[] = []; function* requestWithCleanup(): Generator { try { - yield { method: "unknown", params: null } as unknown as APIRequest; + yield { method: "unknown", params: undefined } as unknown as APIRequest; return "unexpected"; } catch { @@ -1051,7 +1062,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => }); test("transparently paginates batch responses", () => { - const api = spawnAPI(undefined, { maxResponseBytesPerPage: 1 }); + const api = spawnAPI(/*files*/ undefined, { maxResponseBytesPerPage: 1 }); try { const [strict, config, noImplicitAny] = api.batch( api.parseCommandLine.gen(["--strict"]), @@ -1185,6 +1196,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("omits deferred results in any batch position", () => { const api = spawnAPI(); let synchronousWorkCompleted = false; + // eslint-disable-next-line require-yield -- Exercise synchronous completion. function* synchronousWork() { synchronousWorkCompleted = true; return "ignored"; @@ -1211,7 +1223,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const events: string[] = []; function* requestWithCleanup(): Generator { try { - yield { method: "unknown", params: null } as unknown as APIRequest; + yield { method: "unknown", params: undefined } as unknown as APIRequest; } catch { events.push("caught"); @@ -1233,6 +1245,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("batch execution deduplicates only initialize requests within a round", () => { const requestBatches: string[][] = []; function* request(method: string): Generator { + // eslint-disable-next-line no-restricted-syntax -- Initialize requests require null parameters. return yield { method, params: null } as unknown as APIRequest; } @@ -1250,6 +1263,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("does not execute an empty request round", () => { let executions = 0; + // eslint-disable-next-line require-yield -- Exercise synchronous completion. function* completed(value: string) { return value; } @@ -1275,13 +1289,16 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const requestBatches: string[][] = []; function* groupedRequests(): Generator { const responses = yield [ + // eslint-disable-next-line no-restricted-syntax -- Initialize requests require null parameters. { method: "initialize", params: null }, - { method: "other", params: null }, + { method: "other", params: undefined }, + // eslint-disable-next-line no-restricted-syntax -- Initialize requests require null parameters. { method: "initialize", params: null }, ] as unknown as readonly APIRequest[]; return responses.map(response => response.result); } function* initializeRequest(): Generator { + // eslint-disable-next-line no-restricted-syntax -- Initialize requests require null parameters. return yield { method: "initialize", params: null } as unknown as APIRequest; } @@ -1298,15 +1315,15 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => const requestBatches: string[][] = []; function* recoveringRequest(): Generator { try { - yield { method: "bad", params: null } as unknown as APIRequest; + yield { method: "bad", params: undefined } as unknown as APIRequest; } catch { - return yield { method: "recovery", params: null } as unknown as APIRequest; + return yield { method: "recovery", params: undefined } as unknown as APIRequest; } return "unexpected"; } function* successfulRequest(): Generator { - return yield { method: "good", params: null } as unknown as APIRequest; + return yield { method: "good", params: undefined } as unknown as APIRequest; } const results = executeRequestGenerators([recoveringRequest(), successfulRequest()], requests => { @@ -1321,17 +1338,17 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("executes recursively deferred generators", () => { const events: string[] = []; function* grandchild() { - yield { method: "grandchild", params: null } as unknown as APIRequest; + yield { method: "grandchild", params: undefined } as unknown as APIRequest; events.push("grandchild completed"); } function* child() { yield* defer(grandchild()); - yield { method: "child", params: null } as unknown as APIRequest; + yield { method: "child", params: undefined } as unknown as APIRequest; events.push("child completed"); } function* parent() { yield* defer(child()); - yield { method: "parent", params: null } as unknown as APIRequest; + yield { method: "parent", params: undefined } as unknown as APIRequest; events.push("parent completed"); } @@ -1343,7 +1360,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("surfaces deferred errors after the parent completes", () => { const events: string[] = []; function* background() { - yield { method: "background", params: null } as unknown as APIRequest; + yield { method: "background", params: undefined } as unknown as APIRequest; } function* parent() { yield* defer(background()); @@ -1360,11 +1377,11 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("appends deferred work after the parent request", () => { const requestBatches: string[][] = []; function* background() { - yield { method: "background", params: null } as unknown as APIRequest; + yield { method: "background", params: undefined } as unknown as APIRequest; } function* parent() { yield* defer(background()); - yield { method: "parent", params: null } as unknown as APIRequest; + yield { method: "parent", params: undefined } as unknown as APIRequest; } executeRequestGenerators([parent()], requests => { @@ -1377,7 +1394,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => test("rejects repeated generator instances", () => { function* request(): Generator { - return yield { method: "request", params: null } as unknown as APIRequest; + return yield { method: "request", params: undefined } as unknown as APIRequest; } const generator = request(); @@ -1420,8 +1437,8 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => project.program.getSourceFileNames.gen(), ); assert.strictEqual(defaultProject, project); - assert.ok(sourceFileNames.includes(toRootedFilePath("/src/foo.ts", undefined))); - assert.ok(sourceFileNames.includes(toRootedFilePath("/src/index.ts", undefined))); + assert.ok(sourceFileNames.includes(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined))); + assert.ok(sourceFileNames.includes(toRootedFilePath("/src/index.ts", /*currentDirectory*/ undefined))); const [symbol, type] = api.batch( project.checker.getSymbolAtLocation.gen(node), @@ -1909,7 +1926,7 @@ describe("API - generator batching", { concurrency: areTestsFiltered() }, () => assertPublicGeneratorCoverage([ { name: "API", value: api }, - { name: "API", value: api.constructor as object, own: true }, + { name: "API", value: api.constructor, own: true }, { name: "DebugHandlers", value: api.debug }, { name: "Snapshot", value: snapshot }, { name: "ModuleResolver", value: moduleResolver }, diff --git a/packages/typescript/test/sync/api.test.ts b/packages/typescript/test/sync/api.test.ts index caeabc14aa17e..257d6a34a9908 100644 --- a/packages/typescript/test/sync/api.test.ts +++ b/packages/typescript/test/sync/api.test.ts @@ -56,7 +56,6 @@ import { type PathKey, type PropertyAccessExpression, type RootedFilePath, - type SourceFile, SyntaxKind, TokenFlags, tryGetAmbientModuleNameFromSymbolName, @@ -410,7 +409,7 @@ function g(before = 1, required: number, after = 2, ...rest: number[]) {} describe("API", { concurrency }, () => { test("getCurrentLanguageServerSnapshot is LSP-only", () => { - if (!!false) { + function _checkTypes() { using standalone = new API(); // @ts-expect-error The standalone API has no canonical language server state. void standalone.getCurrentLanguageServerSnapshot(); @@ -426,7 +425,7 @@ describe("API", { concurrency }, () => { }], }); const baseSnapshot = undefined! as Snapshot; - void lsp.getCurrentLanguageServerSnapshot(undefined, baseSnapshot); + void lsp.getCurrentLanguageServerSnapshot(/*args*/ undefined, baseSnapshot); void standalone.createSnapshot({ createPrograms: [{ rootFiles: [], compilerOptions: {}, options: { projectReferences: [{ path: "/tsconfig.json" }] } }] }); void standalone.createModuleResolver({ outDir: "dist", rootDirs: ["src"], typeRoots: ["types"] }); @@ -448,7 +447,7 @@ describe("API", { concurrency }, () => { // @ts-expect-error Snapshot update parameters are excess-property checked. void baseSnapshot.update({ fileChanges: { changed: ["/index.ts"] } }); // @ts-expect-error Snapshot updates require an explicit changes object. - void baseSnapshot.update(undefined); + void baseSnapshot.update(/*params*/ undefined); // @ts-expect-error Language server snapshot parameters are excess-property checked. void lsp.getCurrentLanguageServerSnapshot({ fileChanges: { changed: ["/index.ts"] } }); @@ -650,7 +649,7 @@ describe("API", { concurrency }, () => { ); assert.deepEqual(config.fileNames, ["/src/index.ts"]); assert.equal(config.options.strict, true); - assert.equal("configFilePath" in config.options, false); + assert.equal(Reflect.has(config.options, "configFilePath"), false); assert.equal(config.compileOnSave, false); assert.deepEqual(config.errors, []); }); @@ -658,7 +657,8 @@ describe("API", { concurrency }, () => { test("parseJsonConfigFileContent accepts non-object JSON", () => { using api = spawnAPI(); - const config = api.parseJsonConfigFileContent(null, { configDirectory: "/src" }); + // eslint-disable-next-line no-restricted-syntax -- Exercise a null JSON configuration. + const config = api.parseJsonConfigFileContent(/*json*/ null, { configDirectory: "/src" }); assert.deepEqual([...config.fileNames].sort(), ["/src/foo.ts", "/src/index.ts"]); assert.deepEqual(config.errors, []); }); @@ -708,6 +708,7 @@ describe("API", { concurrency }, () => { using api = spawnAPI(); const config = api.parseJsonConfigFileContent( + // eslint-disable-next-line no-restricted-syntax -- Exercise invalid null JSON array elements. { files: [null], include: [null], exclude: [null] }, { configDirectory: "/src" }, ); @@ -825,7 +826,7 @@ describe("API", { concurrency }, () => { test("getSymbol rejects synthesized declarations", () => { using api = spawnAPI(); - const local = createVariableDeclaration(createIdentifier("local"), undefined, undefined, undefined); + const local = createVariableDeclaration(createIdentifier("local"), /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); assert.throws(() => getSymbol(local), /Source file not found/); assert.throws(() => api.getSymbol(local), /Source file not found/); @@ -836,7 +837,7 @@ describe("API", { concurrency }, () => { const deepClone = getSynthesizedDeepClone(declaration); assert.throws(() => getSymbol(shallowClone), /Source file not found/); assert.throws(() => api.getSymbol(deepClone), /Source file not found/); - assert.equal("getSymbol" in declaration, false); + assert.equal(Reflect.has(declaration, "getSymbol"), false); }); test("source files own separate declaration result and request caches", () => { @@ -978,13 +979,13 @@ describe("API", { concurrency }, () => { const parsed = parseNodeHandleFromCompiler(getNodeId(declaration)); assert.equal(getNodeRequestHandle(declaration), `${parsed.index}.#${parsed.sourceFileId}`); - fs.writeFile!(toRootedFilePath("/other.ts", undefined), "export const other = 2;"); + fs.writeFile(toRootedFilePath("/other.ts", /*currentDirectory*/ undefined), "export const other = 2;"); const unchanged = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/other.ts"] } }); const unchangedProject = unchanged.getConfiguredProject("/tsconfig.json")!; assert.ok(unchangedProject.checker.getTypeAtLocation(declaration)); assert.strictEqual(handle.resolve(unchangedProject), declaration); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export function f() { return 'changed'; }"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export function f() { return 'changed'; }"); const changed = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/index.ts"] } }); const changedProject = changed.getConfiguredProject("/tsconfig.json")!; assert.throws(() => changedProject.checker.getTypeAtLocation(declaration), /could not be resolved/); @@ -1054,8 +1055,8 @@ describe("API", { concurrency }, () => { }); assert.equal(snapshot.getProjects().length, 2); assert.deepEqual(snapshot.getProjects().map(project => project.parsedCommandLine.fileNames), [["/src/a.ts"], ["/src/b.ts"]]); - assert.equal(snapshot.operation.createdPrograms!.length, 2); - for (const program of snapshot.operation.createdPrograms!) { + assert.equal(snapshot.operation.createdPrograms.length, 2); + for (const program of snapshot.operation.createdPrograms) { const syntheticProjectId: SyntheticProjectId = program.id; void syntheticProjectId; assert.strictEqual(snapshot.getProgram(program.id), program); @@ -1080,7 +1081,8 @@ describe("API", { concurrency }, () => { if ( method === "release" && typeof params === "object" - && params !== null + && params != undefined + // eslint-disable-next-line local/no-in-operator -- Narrow the request parameters. && "snapshot" in params && params.snapshot === snapshot.id && duplicateReference @@ -1089,7 +1091,8 @@ describe("API", { concurrency }, () => { return true; } const response = apiRequest(method, params); - if (method !== "updateSnapshot" || typeof response !== "object" || response === null) return response; + if (method !== "updateSnapshot" || typeof response !== "object" || response == undefined) return response; + // eslint-disable-next-line local/no-in-operator -- Narrow the response. if (!("snapshot" in response) || typeof response.snapshot !== "number") return response; apiRequest("release", { snapshot: response.snapshot }); duplicateReference = true; @@ -1130,9 +1133,9 @@ describe("API", { concurrency }, () => { }); test("snapshot.update reconfigures module resolution providers", () => { - const root = toRootedFilePath("/src/index.ts", undefined); - const providedA = toRootedFilePath("/a.d.ts", undefined); - const providedB = toRootedFilePath("/b.d.ts", undefined); + const root = toRootedFilePath("/src/index.ts", /*currentDirectory*/ undefined); + const providedA = toRootedFilePath("/a.d.ts", /*currentDirectory*/ undefined); + const providedB = toRootedFilePath("/b.d.ts", /*currentDirectory*/ undefined); const { api: disposableAPI, fs } = spawnAPIWithFS({ [root]: `import { value } from "pkg"; export { value };`, [providedA]: `export declare const value: "a";`, @@ -1160,10 +1163,10 @@ describe("API", { concurrency }, () => { }); const initial = api.createSnapshot({ createPrograms: [createProgram(resolverA)] }); - const programId = initial.operation.createdPrograms![0].id; + const programId = initial.operation.createdPrograms[0].id; assert.deepEqual([...initial.getProgram(programId)!.getSourceFileNames()].sort(), [providedA, root]); assert.equal( - (resolverA.resolveModuleName("pkg", "/src", undefined, { snapshot: initial })).resolvedModule?.resolvedFileName, + (resolverA.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: initial })).resolvedModule?.resolvedFileName, providedA, ); assert.equal((resolverA.resolveModuleName("pkg", "/src")).resolvedModule?.resolvedFileName, providedA); @@ -1173,7 +1176,7 @@ describe("API", { concurrency }, () => { }); assert.deepEqual([...sameSet.getProgram(programId)!.getSourceFileNames()].sort(), [providedA, root]); - fs.writeFile!(root, `import { value } from "pkg"; export const updated = value;`); + fs.writeFile(root, `import { value } from "pkg"; export const updated = value;`); const sameSetAfterEdit = sameSet.update({ reconfigurePrograms: [{ id: programId, ...createProgram(resolverA) }], fileNotifications: { changed: [root] }, @@ -1186,7 +1189,7 @@ describe("API", { concurrency }, () => { assert.deepEqual([...changedSet.getProgram(programId)!.getSourceFileNames()].sort(), [providedB, root]); const removedSet = sameSetAfterEdit.update({ - reconfigurePrograms: [{ id: programId, ...createProgram(undefined) }], + reconfigurePrograms: [{ id: programId, ...createProgram(/*moduleResolver*/ undefined) }], }); assert.deepEqual(removedSet.getProgram(programId)!.getSourceFileNames(), [root]); @@ -1208,7 +1211,7 @@ describe("API", { concurrency }, () => { const callbackSnapshot = api.createSnapshot({ createPrograms: [createProgram(callbackResolver)], }); - const callbackProgramId = callbackSnapshot.operation.createdPrograms![0].id; + const callbackProgramId = callbackSnapshot.operation.createdPrograms[0].id; const repeatedCallback = callbackSnapshot.update({ reconfigurePrograms: [{ id: callbackProgramId, ...createProgram(callbackResolver) }], }); @@ -1225,13 +1228,13 @@ describe("API", { concurrency }, () => { tsBuildInfoFile: "cache/build.tsbuildinfo", typeRoots: ["types"], }); - const result = resolver.resolveModuleName("./missing", "/src", undefined); + const result = resolver.resolveModuleName("./missing", "/src", /*resolutionMode*/ undefined); assert.equal(result.resolvedModule, undefined); }); test("module resolver runs against snapshots or the host filesystem", () => { - const packageJson = toRootedFilePath("/node_modules/pkg/package.json", undefined); - const packageB = toRootedFilePath("/node_modules/pkg/b.d.ts", undefined); + const packageJson = toRootedFilePath("/node_modules/pkg/package.json", /*currentDirectory*/ undefined); + const packageB = toRootedFilePath("/node_modules/pkg/b.d.ts", /*currentDirectory*/ undefined); const { api: disposableAPI, fs } = spawnAPIWithFS({ [packageJson]: JSON.stringify({ name: "pkg", version: "1.0.0", types: "a.d.ts" }), "/node_modules/pkg/a.d.ts": `export declare const value: "a";`, @@ -1243,12 +1246,12 @@ describe("API", { concurrency }, () => { }); const firstSnapshot = api.createSnapshot(); assert.equal( - (resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/a.d.ts", undefined), + (resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/a.d.ts", /*currentDirectory*/ undefined), ); - fs.writeFile!(packageJson, JSON.stringify({ name: "pkg", version: "1.0.0", types: "b.d.ts" })); - fs.writeFile!(packageB, `export declare const value: "b";`); + fs.writeFile(packageJson, JSON.stringify({ name: "pkg", version: "1.0.0", types: "b.d.ts" })); + fs.writeFile(packageB, `export declare const value: "b";`); const secondSnapshot = firstSnapshot.update({ fileNotifications: { changed: [packageJson], @@ -1257,12 +1260,12 @@ describe("API", { concurrency }, () => { }); assert.equal( - (resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/a.d.ts", undefined), + (resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: firstSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/a.d.ts", /*currentDirectory*/ undefined), ); assert.equal( - (resolver.resolveModuleName("pkg", "/src", undefined, { snapshot: secondSnapshot })).resolvedModule?.resolvedFileName, - toRootedFilePath("/node_modules/pkg/b.d.ts", undefined), + (resolver.resolveModuleName("pkg", "/src", /*resolutionMode*/ undefined, { snapshot: secondSnapshot })).resolvedModule?.resolvedFileName, + toRootedFilePath("/node_modules/pkg/b.d.ts", /*currentDirectory*/ undefined), ); assert.equal( (resolver.resolveModuleName("pkg", "/src")).resolvedModule?.resolvedFileName, @@ -1443,7 +1446,7 @@ import "pkg/feature";`, }); assert.deepEqual( - [...snapshot.operation.createdPrograms![0].getSourceFileNames()].sort(), + [...snapshot.operation.createdPrograms[0].getSourceFileNames()].sort(), ["/node_modules/@types/resolver-types/index.d.ts", "/node_modules/pkg/dist/feature.d.ts", "/src/index.ts"], ); }); @@ -1601,7 +1604,8 @@ declare module "augmentation" {}`, }; // @ts-expect-error raw path strings are not finalized compiler options const _finalizedOptions: CompilerOptions = rawOptions; - const _rawOptions: RawCompilerOptions = undefined! as CompilerOptions; + const finalizedOptions: CompilerOptions = undefined!; + const _rawOptions: RawCompilerOptions = finalizedOptions; const program = api.createProgram(["/src/index.ts", "/src/component.vue"], rawOptions); const compilerOptions: CompilerOptions = program.getCompilerOptions(); @@ -1611,14 +1615,14 @@ declare module "augmentation" {}`, { noLib: true, allowNonTsExtensions: true, - outDir: toRootedDirectoryPath(resolve(serverCurrentDirectory, "dist"), undefined), + outDir: toRootedDirectoryPath(resolve(serverCurrentDirectory, "dist"), /*currentDirectory*/ undefined), paths: { "*a": ["/src/first.ts"], "*": ["/src/fallback.ts"] }, rootDirs: [ - toRootedDirectoryPath(resolve(serverCurrentDirectory, "src"), undefined), - toRootedDirectoryPath(resolve(serverCurrentDirectory, "generated"), undefined), + toRootedDirectoryPath(resolve(serverCurrentDirectory, "src"), /*currentDirectory*/ undefined), + toRootedDirectoryPath(resolve(serverCurrentDirectory, "generated"), /*currentDirectory*/ undefined), ], suppressOutputPathCheck: true, - tsBuildInfoFile: toRootedFilePath(resolve(serverCurrentDirectory, "cache/build.tsbuildinfo"), undefined), + tsBuildInfoFile: toRootedFilePath(resolve(serverCurrentDirectory, "cache/build.tsbuildinfo"), /*currentDirectory*/ undefined), } satisfies CompilerOptions, ); assert.equal((program.getSemanticDiagnostics("/src/index.ts")).length, 0); @@ -1861,8 +1865,8 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); }); test("returns diagnostics in build response information", () => { @@ -1912,8 +1916,9 @@ describe("BuildOrchestrator", () => { const cleanResp1 = orchestrator.clean("/a/tsconfig.json"); assert.equal(cleanResp1.status, 0); - assert.deepEqual(cleanResp1.diagnostics, undefined); - assert.deepEqual(cleanResp1.filesDeleted!.sort(), [ + assert.deepEqual(cleanResp1.diagnostics, /*expected*/ undefined); + cleanResp1.filesDeleted!.sort(); + assert.deepEqual(cleanResp1.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -1922,14 +1927,15 @@ describe("BuildOrchestrator", () => { assert.equal(cleanResp1.statistics.ProjectsBuilt, 0); const buildResp1 = orchestrator.build("/a/tsconfig.json"); assert.equal(buildResp1.status, 0); - assert.deepEqual(buildResp1.diagnostics, undefined); + assert.deepEqual(buildResp1.diagnostics, /*expected*/ undefined); assert.equal(buildResp1.statistics.Projects, 1); assert.equal(buildResp1.statistics.ProjectsBuilt, 1); const cleanRefResp = orchestrator.cleanReferences("/c/tsconfig.json"); assert.equal(cleanRefResp.status, 0); - assert.deepEqual(cleanRefResp.diagnostics, undefined); - assert.deepEqual(cleanRefResp.filesDeleted!.sort(), [ + assert.deepEqual(cleanRefResp.diagnostics, /*expected*/ undefined); + cleanRefResp.filesDeleted!.sort(); + assert.deepEqual(cleanRefResp.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -1941,12 +1947,13 @@ describe("BuildOrchestrator", () => { assert.equal(cleanRefResp.statistics.ProjectsBuilt, 0); const buildRefsResp = orchestrator.buildReferences("/c/tsconfig.json"); assert.equal(buildRefsResp.status, 0); - assert.deepEqual(buildRefsResp.diagnostics, undefined); + assert.deepEqual(buildRefsResp.diagnostics, /*expected*/ undefined); const cleanResp2 = orchestrator.clean(); assert.equal(cleanResp2.status, 0); - assert.deepEqual(cleanResp2.diagnostics, undefined); - assert.deepEqual(cleanResp2.filesDeleted!.sort(), [ + assert.deepEqual(cleanResp2.diagnostics, /*expected*/ undefined); + cleanResp2.filesDeleted!.sort(); + assert.deepEqual(cleanResp2.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", "/a/tsconfig.tsbuildinfo", @@ -1961,7 +1968,7 @@ describe("BuildOrchestrator", () => { assert.equal(cleanResp2.statistics.ProjectsBuilt, 0); const buildResp2 = orchestrator.build(); assert.equal(buildResp2.status, 0); - assert.deepEqual(buildResp2.diagnostics, undefined); + assert.deepEqual(buildResp2.diagnostics, /*expected*/ undefined); assert.equal(buildResp2.statistics.Projects, 3); assert.equal(buildResp2.statistics.ProjectsBuilt, 3); }); @@ -1981,15 +1988,16 @@ describe("BuildOrchestrator", () => { const response = orchestrator.clean(); assert.equal(response.status, 0); - assert.deepEqual(response.diagnostics, undefined); - assert.deepEqual(response.filesDeleted!.sort(), [ + assert.deepEqual(response.diagnostics, /*expected*/ undefined); + response.filesDeleted!.sort(); + assert.deepEqual(response.filesDeleted, [ "/a/dist/index.d.ts", "/a/dist/index.js", ]); assert.equal(response.statistics.Projects, 1); assert.equal(response.statistics.ProjectsBuilt, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.d.ts", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.d.ts", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("rebuilds projects after multiple file system changes", () => { @@ -2002,24 +2010,24 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 10;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 10;`); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 20;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 20;`); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 20/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 20/); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 100;`); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 200;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 100;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 200;`); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 100/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 200/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 100/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 200/); }); test("clean removes build outputs", () => { @@ -2032,13 +2040,13 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((orchestrator.clean()).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("builds and cleans selected projects after file system changes", () => { @@ -2051,35 +2059,35 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build("/a/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); - fs.writeFile!(toRootedFilePath("/a/src/index.ts", undefined), `export const a = 10;`); + fs.writeFile(toRootedFilePath("/a/src/index.ts", /*currentDirectory*/ undefined), `export const a = 10;`); assert.equal((orchestrator.build("/b/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); - fs.writeFile!(toRootedFilePath("/b/src/index.ts", undefined), `export const b = 20;`); + fs.writeFile(toRootedFilePath("/b/src/index.ts", /*currentDirectory*/ undefined), `export const b = 20;`); assert.equal((orchestrator.clean("/a/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.match(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))!, /export const c = 3/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.match(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), /export const c = 3/); assert.equal((orchestrator.clean("/b/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 10/); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.match(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))!, /export const c = 3/); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 10/); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), /export const c = 3/); - fs.writeFile!(toRootedFilePath("/b/dist/index.js", undefined), `export const b = 2`); + fs.writeFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined), `export const b = 2`); assert.equal((orchestrator.clean("/b/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("builds only references of a selected project", () => { @@ -2087,7 +2095,7 @@ describe("BuildOrchestrator", () => { ...files, }); using api = disposableApi; - const options = api.parseCommandLine([]); + api.parseCommandLine([]); // @ts-ignore -- Internal API exercised by source tests. const orchestrator = api.createBuildOrchestrator( ["/c/tsconfig.json"], @@ -2095,9 +2103,9 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.buildReferences("/c/tsconfig.json")).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))!, /export const a = 1/); - assert.match(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))!, /export const b = 2/); - assert.equal(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), /export const a = 1/); + assert.match(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), /export const b = 2/); + assert.equal(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("cleans only references of a selected project", () => { @@ -2112,22 +2120,22 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((orchestrator.cleanReferences("/c/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((orchestrator.build()).status, 0); - assert.ok(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined))); - assert.ok(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined))); + assert.ok(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined))); + assert.ok(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined))); assert.equal((orchestrator.cleanReferences()).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/a/dist/index.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile!(toRootedFilePath("/b/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/c/dist/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/a/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/b/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/c/dist/index.js", /*currentDirectory*/ undefined))); }); test("handles invalidated projects and cleans the last built configuration", () => { @@ -2152,24 +2160,24 @@ describe("BuildOrchestrator", () => { ); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined))!, /export const d = 4/); + assert.match(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), /export const d = 4/); - fs.writeFile!( - toRootedFilePath("/d/tsconfig.json", undefined), + fs.writeFile( + toRootedFilePath("/d/tsconfig.json", /*currentDirectory*/ undefined), JSON.stringify({ compilerOptions: { composite: true, outDir: "lib", rootDir: "src" }, files: ["src/index.ts"], }), ); - fs.writeFile!(toRootedFilePath("/d/lib/index.js", undefined), `export const d = 40;`); + fs.writeFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined), `export const d = 40;`); assert.equal((orchestrator.clean("/d/tsconfig.json")).status, 0); - assert.equal(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined)), serverFS.useOS); - assert.ok(fs.readFile!(toRootedFilePath("/d/lib/index.js", undefined))); + assert.equal(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.ok(fs.readFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined))); assert.equal((orchestrator.build()).status, 0); - assert.match(fs.readFile!(toRootedFilePath("/d/lib/index.js", undefined))!, /export const d = 4/); - assert.equal(fs.readFile!(toRootedFilePath("/d/dist/index.js", undefined)), serverFS.useOS); + assert.match(fs.readFile(toRootedFilePath("/d/lib/index.js", /*currentDirectory*/ undefined)), /export const d = 4/); + assert.equal(fs.readFile(toRootedFilePath("/d/dist/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); }); @@ -2258,7 +2266,7 @@ test(); const project = snapshot.getConfiguredProject("/tsconfig.json")!; const sourceFile = project.program.getSourceFile("/src/main.ts"); assert.ok(sourceFile); - const nodes: Array = []; + const nodes: Node[] = []; sourceFile.forEachChild(node => { if (isExpressionStatement(node) && isCallExpression(node.expression) && node.expression.typeArguments) { nodes.push(node.expression.typeArguments[0]); @@ -2833,9 +2841,9 @@ describe("SourceFile", { concurrency }, () => { "/src/dependency.ts": `export const value = 1;`, }); using program = api.createProgram(["/src/main.ts"], { noLib: true }); - assert.ok(!("getTypeChecker" in program)); - assert.ok(!("getResolvedProjectReferences" in program)); - assert.ok(!("getSourceFiles" in program)); + assert.ok(!Reflect.has(program, "getTypeChecker")); + assert.ok(!Reflect.has(program, "getResolvedProjectReferences")); + assert.ok(!Reflect.has(program, "getSourceFiles")); assert.deepEqual(program.getRootFileNames(), ["/src/main.ts"]); assert.deepEqual(program.getSourceFileNames(), ["/src/dependency.ts", "/src/main.ts"]); assert.equal(program.getProjectReferences(), undefined); @@ -2923,7 +2931,7 @@ export const other: { value: string } = box;`, const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); const project = snapshot.getConfiguredProject("/tsconfig.json")!; for (const method of ["containsFile", "getFileNames", "getRootFiles", "hasRoots", "isRoot", "hasConfigFile", "getSourceFile"]) { - assert.ok(!(method in project), `Project should not expose ${method}`); + assert.ok(!Reflect.has(project, method), `Project should not expose ${method}`); } }); @@ -2955,7 +2963,7 @@ export const other: { value: string } = box;`, typescript: { contentMapper: { exec: [process.execPath, "--input-type=module", "--eval", mapperScript] } }, }), ); - const configFileName = toRootedFilePath(join(directory, "tsconfig.json"), undefined); + const configFileName = toRootedFilePath(join(directory, "tsconfig.json"), /*currentDirectory*/ undefined); writeFileSync( configFileName, JSON.stringify({ @@ -2969,7 +2977,7 @@ export const other: { value: string } = box;`, using api = new API({ cwd: directory, runExternalCode: true }); const snapshot = api.createSnapshot({ openProjects: [configFileName] }); const program = snapshot.getConfiguredProject(configFileName)!.program; - const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), undefined); + const supplementalFileName = toRootedFilePath(join(directory, "app.box.0.ts"), /*currentDirectory*/ undefined); assert.equal(existsSync(supplementalFileName), false); assert.ok(program.getSourceFile(supplementalFileName)); }); @@ -3129,8 +3137,8 @@ export const other: { value: string } = box;`, (function walk(node: Node): void { visited.push({ kind: node.kind, pos: node.pos, end: node.end }); node.forEachChild(walk, (nodes: NodeArray) => { - for (let i = 0; i < nodes.length; i++) { - walk(nodes[i]); + for (const node of nodes) { + walk(node); } return undefined; }); @@ -3199,6 +3207,7 @@ describe("API objects", { concurrency }, () => { test("template unicode escapes", () => { using api = spawnAPI({ "/tsconfig.json": "{}", + // eslint-disable-next-line no-template-curly-in-string -- This string is TypeScript source. "/src/index.ts": "`\\ud800${0}\\udc00`", }); @@ -3295,7 +3304,7 @@ describe("Multiple snapshots", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file and create a new snapshot with the change - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = "changed";`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = "changed";`); const snap2 = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/foo.ts"] }, @@ -3331,7 +3340,7 @@ describe("Multiple snapshots", { concurrency }, () => { const snap1 = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); // Add a brand new file - fs.writeFile!(toRootedFilePath("/src/bar.ts", undefined), `export const bar = true;`); + fs.writeFile(toRootedFilePath("/src/bar.ts", /*currentDirectory*/ undefined), `export const bar = true;`); const snap2 = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { created: ["/src/bar.ts"] }, @@ -3359,7 +3368,7 @@ describe("Multiple snapshots", { concurrency }, () => { ]; for (const version of versions) { - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), version); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), version); const snap = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/foo.ts"] }, @@ -3385,7 +3394,7 @@ describe("Multiple snapshots", { concurrency }, () => { const baseFirst = base.getConfiguredProject("/first/tsconfig.json")!.program.getSourceFile("/first/index.ts"); const baseSecondProject = base.getConfiguredProject("/second/tsconfig.json")!; - fs.writeFile!(toRootedFilePath("/first/index.ts", undefined), `export const first = 2;`); + fs.writeFile(toRootedFilePath("/first/index.ts", /*currentDirectory*/ undefined), `export const first = 2;`); const updated = base.update({ fileNotifications: { changed: ["/first/index.ts"] }, ensurePrograms: [base.getConfiguredProject("/first/tsconfig.json")!.id], @@ -3430,15 +3439,15 @@ describe("Multiple snapshots", { concurrency }, () => { assert.equal(created.getProjects().length, 3); const configuredProjectId: ConfiguredProjectId = created.getConfiguredProject("/configured/tsconfig.json")!.id; void configuredProjectId; - assert.strictEqual(created.operation.openedFiles![0].project, created.getProject(created.operation.openedFiles![0].project.id)); - assert.strictEqual(created.operation.openedFiles![1].project, created.getConfiguredProject("/configured/tsconfig.json")); + assert.strictEqual(created.operation.openedFiles[0].project, created.getProject(created.operation.openedFiles[0].project.id)); + assert.strictEqual(created.operation.openedFiles[1].project, created.getConfiguredProject("/configured/tsconfig.json")); for (const project of created.getProjects()) { assert.equal(project.dirty, false, `${project.id} should be ensured when opened or created`); } - fs.writeFile!(toRootedFilePath("/configured/index.ts", undefined), `export const configured = 2;`); - fs.writeFile!(toRootedFilePath("/inferred.ts", undefined), `export const inferred = 2;`); - fs.writeFile!(toRootedFilePath("/synthetic.ts", undefined), `export const synthetic = 2;`); + fs.writeFile(toRootedFilePath("/configured/index.ts", /*currentDirectory*/ undefined), `export const configured = 2;`); + fs.writeFile(toRootedFilePath("/inferred.ts", /*currentDirectory*/ undefined), `export const inferred = 2;`); + fs.writeFile(toRootedFilePath("/synthetic.ts", /*currentDirectory*/ undefined), `export const synthetic = 2;`); const dirty = created.update({ fileNotifications: { changed: ["/configured/index.ts", "/inferred.ts", "/synthetic.ts"] }, }); @@ -3501,7 +3510,7 @@ describe("Source file caching", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file in the VFS - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = 100;`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = 100;`); // Notify the server about the change const snap2 = api.createSnapshot({ @@ -3525,7 +3534,7 @@ describe("Source file caching", { concurrency }, () => { assert.ok(sf1); // Mutate a different file - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = 999;`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = 999;`); // Notify the server about the change to foo.ts only const snap2 = api.createSnapshot({ @@ -3566,7 +3575,7 @@ describe("Source file caching", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 42;`); // Mutate the file - fs.writeFile!(toRootedFilePath("/src/foo.ts", undefined), `export const foo = "hello";`); + fs.writeFile(toRootedFilePath("/src/foo.ts", /*currentDirectory*/ undefined), `export const foo = "hello";`); // Use invalidateAll to force re-fetch const snap2 = api.createSnapshot({ @@ -3606,7 +3615,7 @@ describe("Source file caching", { concurrency }, () => { assert.ok(type1.flags & TypeFlags.Number); // Snapshot 2: change a different file - fs.writeFile!(toRootedFilePath("/src/other.ts", undefined), `export const x = 2;`); + fs.writeFile(toRootedFilePath("/src/other.ts", /*currentDirectory*/ undefined), `export const x = 2;`); const snap2 = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/other.ts"] }, @@ -4164,7 +4173,7 @@ export class Cache { const sigs = project.checker.getSignaturesOfType(type, SignatureKind.Call); assert.ok(sigs.length > 0); const thisParam = sigs[0].getThisParameter(); - assert.strictEqual(thisParam, undefined, "add() has no explicit this parameter"); + assert.strictEqual(thisParam, /*expected*/ undefined, "add() has no explicit this parameter"); }); test("Signature.getThisParameter() returns symbol for explicit this parameter", () => { @@ -4201,7 +4210,7 @@ export class Cache { const sigs = project.checker.getSignaturesOfType(type, SignatureKind.Call); assert.ok(sigs.length > 0); const target = sigs[0].getTarget(); - assert.strictEqual(target, undefined, "add() is not an instantiated signature"); + assert.strictEqual(target, /*expected*/ undefined, "add() is not an instantiated signature"); }); test("Signature.getTarget() returns the generic source signature for an instantiated call", () => { @@ -4331,10 +4340,11 @@ export const value = 1; const project = snapshot.getConfiguredProject("/tsconfig.json")!; const sourceFile = project.program.getSourceFile("/src/mod.ts"); assert.ok(sourceFile); - using retained = api.retainSourceFile(sourceFile); + using _retained = api.retainSourceFile(sourceFile); const animal = project.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); const storage = animal["storage"]; + // eslint-disable-next-line local/no-in-operator -- Narrow the ownership union. assert.ok("owner" in storage); assert.strictEqual(storage.owner.api, api); assert.deepEqual(Object.keys(storage.owner).sort(), ["api", "record"]); @@ -4568,7 +4578,7 @@ second;`; const animal = firstSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); - fs.writeFile!(toRootedFilePath("/src/other.ts", undefined), `export const other = 2;`); + fs.writeFile(toRootedFilePath("/src/other.ts", /*currentDirectory*/ undefined), `export const other = 2;`); const secondSnapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/other.ts"] } }); const type = secondSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getTypeOfSymbol(animal); assert.ok(type); @@ -4582,7 +4592,7 @@ second;`; const animal = firstSnapshot.getConfiguredProject("/tsconfig.json")!.checker.getSymbolAtPosition("/src/mod.ts", symbolFiles["/src/mod.ts"].indexOf("Animal")); assert.ok(animal); - fs.writeFile!(toRootedFilePath("/src/mod.ts", undefined), `${symbolFiles["/src/mod.ts"]}\nexport const added = 2;`); + fs.writeFile(toRootedFilePath("/src/mod.ts", /*currentDirectory*/ undefined), `${symbolFiles["/src/mod.ts"]}\nexport const added = 2;`); const secondSnapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"], fileNotifications: { changed: ["/src/mod.ts"] } }); const secondProject = secondSnapshot.getConfiguredProject("/tsconfig.json")!; assert.throws(() => secondProject.checker.getTypeOfSymbol(animal), /source file is not part of the requested program/); @@ -4650,7 +4660,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("TypeReference.getTarget() returns the generic target", () => { const { type, api: disposableAPI } = getTypeAtName(spawnAPI(typeFiles), "arr:"); - using api = disposableAPI; + using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Object); const ref = type as TypeReference; @@ -4673,7 +4683,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("UnionOrIntersectionType.getTypes() returns union members", () => { const { type, api: disposableAPI } = getTypeAtName(spawnAPI(typeFiles), "union:"); - using api = disposableAPI; + using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Union); const union = type as UnionOrIntersectionType; @@ -4686,7 +4696,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("UnionOrIntersectionType.getTypes() returns intersection members", () => { const { type, api: disposableAPI } = getTypeAtName(spawnAPI(typeFiles), "intersection:"); - using api = disposableAPI; + using _api = disposableAPI; assert.ok(type.flags & TypeFlags.Intersection); const inter = type as UnionOrIntersectionType; @@ -4831,7 +4841,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; test("TemplateLiteralType.texts and getTypes()", () => { const { type, api: disposableAPI } = getTypeAtName(spawnAPI(typeFiles), "tpl:"); - using api = disposableAPI; + using _api = disposableAPI; assert.ok(type.flags & TypeFlags.TemplateLiteral, `Expected TemplateLiteralType, got flags ${type.flags}`); const tpl = type as TemplateLiteralType; @@ -4896,7 +4906,7 @@ array([]); assert.equal(type.isTupleType(), true); assert.equal(type.isTupleTypeTarget(), false); assert.ok(type.isTupleType()); - assert.equal(Reflect.get(type, "fixedLength"), undefined); + assert.equal((type as { fixedLength?: unknown; }).fixedLength, undefined); const target = type.getTarget(); assert.ok(target.objectFlags & ObjectFlags.Tuple); @@ -5170,7 +5180,7 @@ describe("Checker - literal and nullable type getters", { concurrency }, () => { assert.ok(withBoth.flags & TypeFlags.Union, `Expected union, got flags ${withBoth.flags}`); // Adding no flags should just return the original type unchanged. - const withNeither = project.checker.getNullableType(stringType, 0 as TypeFlags); + const withNeither = project.checker.getNullableType(stringType, 0); assert.equal(withNeither.id, stringType.id); }); @@ -5609,6 +5619,7 @@ describe("readFile callback semantics", { concurrency }, () => { ...createVirtualFileSystem({ "/tsconfig.json": "{}", }), + // eslint-disable-next-line no-restricted-syntax -- A null result must not mean a missing file. readFile: (() => null) as unknown as FileSystemCallbacks["readFile"], }; using api = new API({ cwd: "/", fs }); @@ -5641,7 +5652,7 @@ describe("readFile callback semantics", { concurrency }, () => { using snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); assert.ok( (snapshot.getConfiguredProject("/tsconfig.json")!.program.getSourceFileNames()) - .includes(toRootedFilePath("/node_modules/pkg/index.d.ts", undefined)), + .includes(toRootedFilePath("/node_modules/pkg/index.d.ts", /*currentDirectory*/ undefined)), ); } }); @@ -5794,19 +5805,19 @@ describe("updateSnapshot file systems", { concurrency }, () => { const fs: FileSystemCallbacks = { readFile: path => { callbackCalls.push(`readFile:${path}`); - return host.readFile!(path); + return host.readFile(path); }, fileExists: path => { callbackCalls.push(`fileExists:${path}`); - return host.fileExists!(path); + return host.fileExists(path); }, directoryExists: path => { callbackCalls.push(`directoryExists:${path}`); - return host.directoryExists!(path); + return host.directoryExists(path); }, getAccessibleEntries: path => { callbackCalls.push(`getAccessibleEntries:${path}`); - return host.getAccessibleEntries!(path); + return host.getAccessibleEntries(path); }, realpath: path => { callbackCalls.push(`realpath:${path}`); @@ -5820,7 +5831,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { }, writeFile: (path, content) => { callbackCalls.push(`writeFile:${path}`); - host.writeFile!(path, content); + host.writeFile(path, content); }, removeFile: path => { callbackCalls.push(`removeFile:${path}`); @@ -5919,11 +5930,11 @@ describe("updateSnapshot file systems", { concurrency }, () => { ...host, readFile: path => { readFileCalls.push(path); - return host.readFile!(path); + return host.readFile(path); }, getAccessibleEntries: path => { directoryCalls.push(path); - return host.getAccessibleEntries!(path); + return host.getAccessibleEntries(path); }, }; using api = new API({ @@ -6174,7 +6185,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { const programId = target.operation.createdPrograms[0].id; const originalFile = target.getProgram(programId)!.getSourceFile("/index.ts"); assert.equal(originalFile!.text, "export const value = 1;"); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); using source = api.createSnapshot({ fileSystem: createFileSystemLayer([["/index.ts", "export const value = 2;"]]), }); @@ -6222,7 +6233,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { }); const programId = original.operation.createdPrograms[0].id; using target = original.update({}); - fs.writeFile!(toRootedFilePath("/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); const changes = { fileNotifications: { invalidateAll: true }, ensurePrograms: true } as const; using updated = original.update(changes); assert.equal((updated.getProgram(programId)!.getSourceFile("/index.ts"))!.text, "export const value = 2;"); @@ -6280,7 +6291,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { using moreExtras = extras.update({ fileSystem: createFileSystemLayer([["/src/second.ts", "export const second = true;"]]), }); - fs.writeFile!(toRootedFilePath("/src/index.ts", undefined), "export const value = 2;"); + fs.writeFile(toRootedFilePath("/src/index.ts", /*currentDirectory*/ undefined), "export const value = 2;"); using newOriginal = original.update({ openProjects: ["/other/tsconfig.json"], ensurePrograms: true, @@ -6471,7 +6482,7 @@ describe("updateSnapshot file systems", { concurrency }, () => { const program = snapshot.getConfiguredProject("/tsconfig.json")!.program; const result = program.emit(); assert.equal(result.fileSystem, undefined); - assert.equal(host.readFile!(toRootedFilePath("/out/main.js", undefined)), `export const value = 1;\n`); + assert.equal(host.readFile(toRootedFilePath("/out/main.js", /*currentDirectory*/ undefined)), `export const value = 1;\n`); }); test("full file system can link node_modules from the host", () => { @@ -6487,16 +6498,16 @@ describe("updateSnapshot file systems", { concurrency }, () => { ...host, directoryExists: path => { directoryExistsCalls.push(path); - return host.directoryExists!(path); + return host.directoryExists(path); }, fileExists: path => { - const exists = host.fileExists!(path); + const exists = host.fileExists(path); fileExistsCalls.push(`${path}:${exists}`); return exists; }, readFile: path => { readFileCalls.push(path); - return host.readFile!(path); + return host.readFile(path); }, }, }); @@ -7060,7 +7071,7 @@ export const n: number = 0; assert.ok(derivedType.isClassOrInterface(), "Derived should be a class/interface type"); const baseTypes = derivedType.getBaseTypes(); assert.ok(baseTypes && baseTypes.length > 0, "class type should have base types"); - const baseSymbol = baseTypes![0].getSymbol(); + const baseSymbol = baseTypes[0].getSymbol(); assert.equal(baseSymbol?.name, "Base"); // A primitive type is not a class/interface, so getBaseTypes() is undefined. @@ -7789,7 +7800,7 @@ describe("Checker - TypeParameter getters", { concurrency }, () => { assert.ok(sigs.length > 0); const typeParams = sigs[0].getTypeParameters(); assert.ok(typeParams.length > 0, "Should have type parameters"); - const typeParam = typeParams[0] as TypeParameter; + const typeParam = typeParams[0]; const constraint = typeParam.getConstraint(); assert.ok(constraint); @@ -7818,7 +7829,7 @@ describe("Checker - TypeParameter getters", { concurrency }, () => { assert.ok(sigs.length > 0); const typeParams = sigs[0].getTypeParameters(); assert.ok(typeParams.length > 0, "Should have type parameters"); - const typeParam = typeParams[0] as TypeParameter; + const typeParam = typeParams[0]; assert.equal(typeParam.getConstraint(), undefined); assert.equal(typeParam.getDefault(), undefined); @@ -8653,7 +8664,7 @@ describe("FreshableType - getFreshType and getRegularType", { concurrency }, () assert.ok(regular.flags & TypeFlags.Enum, "Regular enum type should also have TypeFlags.Enum"); assert.notEqual(regular.id, type.id, "Regular type should be distinct from the fresh type"); // Round-trip: regular → getFreshType() → back to the original fresh type - const backToFresh = (regular as FreshableType).getFreshType(); + const backToFresh = regular.getFreshType(); assert.ok(backToFresh); assert.equal(backToFresh.id, type.id, "Round-trip through regular/fresh returns the original type"); }); @@ -8814,7 +8825,7 @@ export const obj = { m: 1, s: "hi", b: true }; using lease = api.createSourceFile("/test.ts", "/** leading comment */\nfoo();\n/* @__PURE__ */ baz();\n"); const { sourceFile } = lease; const added = createExpressionStatement( - createCallExpression(createIdentifier("bar"), undefined, undefined, [createStringLiteral("x", TokenFlags.None)], NodeFlags.None), + createCallExpression(createIdentifier("bar"), /*questionDotToken*/ undefined, /*typeArguments*/ undefined, [createStringLiteral("x", TokenFlags.None)], NodeFlags.None), ); const updated = updateSourceFile(sourceFile, [added, ...sourceFile.statements], sourceFile.endOfFileToken); const expected = 'bar("x");\n/** leading comment */\nfoo();\n/* @__PURE__ */ baz();\n'; @@ -8862,7 +8873,7 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createUnionTypeNode([ createKeywordTypeNode(SyntaxKind.StringKeyword), createKeywordTypeNode(SyntaxKind.NumberKeyword), @@ -8875,17 +8886,17 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const param = createParameterDeclaration( - undefined, - undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, createIdentifier("x"), - undefined, + /*questionToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), - undefined, + /*initializer*/ undefined, ); const node = createFunctionTypeNode( - undefined, + /*typeParameters*/ undefined, [param], createKeywordTypeNode(SyntaxKind.NumberKeyword), ); @@ -8897,7 +8908,7 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createTypeReferenceNode(createIdentifier("Array"), [ createKeywordTypeNode(SyntaxKind.StringKeyword), ]); @@ -8909,7 +8920,7 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createArrayTypeNode(createKeywordTypeNode(SyntaxKind.NumberKeyword)); const text = api.printer.printNode(node); assert.strictEqual(text, "number[]"); @@ -8946,7 +8957,7 @@ export const obj = { m: 1, s: "hi", b: true }; const symbol = checker.getSymbolAtPosition("/main.ts", 13); assert.strictEqual(symbol?.name, "x"); const type = checker.getTypeOfSymbol(symbol); - assert.strictEqual(checker.typeToTypeNode(type, project.program.getSourceFile("/main.ts")), undefined); + assert.strictEqual(checker.typeToTypeNode(type, project.program.getSourceFile("/main.ts")), /*expected*/ undefined); }); test("visitEachChild on typeToTypeNode result with keyword types", () => { @@ -9143,7 +9154,7 @@ export const obj = { m: 1, s: "hi", b: true }; valueType: info.valueType, isReadonly: false, }, - undefined, + /*enclosingDeclaration*/ undefined, NodeBuilderFlags.WriteArrayAsGenericType, ); assert.ok(synthesized); @@ -9216,7 +9227,7 @@ export const obj = { m: 1, s: "hi", b: true }; assert.ok(symbol); const type = checker.getTypeOfSymbol(symbol); assert.ok(type); - const text = checker.typeToString(type, undefined, TypeFormatFlags.WriteArrayAsGenericType); + const text = checker.typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType); assert.strictEqual(text, "(name: string) => Array"); }); @@ -9255,14 +9266,14 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const stringProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); - const numberProp = createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!); + const stringProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); + const numberProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([stringProp, numberProp]); - emitContext.addSyntheticLeadingComment(typeLiteral, SyntaxKind.SingleLineCommentTrivia, " top", true, false); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a", true, false); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a again", true, false); - emitContext.addSyntheticTrailingComment(numberProp, SyntaxKind.MultiLineCommentTrivia, " nested b ", false, false); + emitContext.addSyntheticLeadingComment(typeLiteral, SyntaxKind.SingleLineCommentTrivia, " top", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " nested a again", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); + emitContext.addSyntheticTrailingComment(numberProp, SyntaxKind.MultiLineCommentTrivia, " nested b ", /*hasTrailingNewLine*/ false, /*hasLeadingNewLine*/ false); assert.deepStrictEqual( emitContext.getSyntheticLeadingComments(stringProp)?.map(c => c.text), @@ -9270,9 +9281,9 @@ export const obj = { m: 1, s: "hi", b: true }; ); assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(numberProp)?.map(c => c.text), [" nested b "]); - assert.deepStrictEqual(emitContext.getSyntheticLeadingComments(numberProp), undefined); - assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(stringProp), undefined); - assert.strictEqual(emitContext.getSyntheticLeadingComments(createIdentifier("untouched")), undefined); + assert.deepStrictEqual(emitContext.getSyntheticLeadingComments(numberProp), /*expected*/ undefined); + assert.deepStrictEqual(emitContext.getSyntheticTrailingComments(stringProp), /*expected*/ undefined); + assert.strictEqual(emitContext.getSyntheticLeadingComments(createIdentifier("untouched")), /*expected*/ undefined); assert.strictEqual(emitContext.getEmitFlags(typeLiteral), 0); const text = api.printer.printNode(typeLiteral, { emitContext }); @@ -9292,10 +9303,10 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const stringProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); + const stringProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([stringProp]); - emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " will be replaced", true, false); + emitContext.addSyntheticLeadingComment(stringProp, SyntaxKind.SingleLineCommentTrivia, " will be replaced", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); emitContext.setSyntheticLeadingComments(stringProp, [ { kind: SyntaxKind.SingleLineCommentTrivia, text: " bulk leading 1", hasTrailingNewLine: true, hasLeadingNewLine: false }, { kind: SyntaxKind.SingleLineCommentTrivia, text: " bulk leading 2", hasTrailingNewLine: true, hasLeadingNewLine: false }, @@ -9344,8 +9355,8 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const typeLiteral = createTypeLiteralNode([ - createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!), - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); assert.strictEqual(api.printer.printNode(typeLiteral), "{\n a: string;\n b: number;\n}"); @@ -9364,7 +9375,7 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const multiLineObject = createObjectLiteralExpression([ - createPropertyAssignment(undefined, createIdentifier("a"), undefined, undefined!, createNumericLiteral("1", 0)), + createPropertyAssignment(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0)), ]); assert.strictEqual(api.printer.printNode(multiLineObject), "{ a: 1 }"); @@ -9385,8 +9396,8 @@ export const obj = { m: 1, s: "hi", b: true }; assert.strictEqual(EmitFlags.NoTokenSourceMaps, EmitFlags.NoTokenLeadingSourceMaps | EmitFlags.NoTokenTrailingSourceMaps); const typeLiteral = createTypeLiteralNode([ - createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!), - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); const emitContext = api.printer.createEmitContext(); assert.strictEqual(emitContext.getEmitFlags(typeLiteral), EmitFlags.None); @@ -9403,12 +9414,12 @@ export const obj = { m: 1, s: "hi", b: true }; using api = spawnAPI(emitterFiles); const emitContext = api.printer.createEmitContext(); - const commentedProp = createPropertySignatureDeclaration(undefined, createIdentifier("a"), undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), undefined!); + const commentedProp = createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("a"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.StringKeyword), /*initializer*/ undefined); const typeLiteral = createTypeLiteralNode([ commentedProp, - createPropertySignatureDeclaration(undefined, createIdentifier("b"), undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), undefined!), + createPropertySignatureDeclaration(/*modifiers*/ undefined, createIdentifier("b"), /*postfixToken*/ undefined, createKeywordTypeNode(SyntaxKind.NumberKeyword), /*initializer*/ undefined), ]); - emitContext.addSyntheticLeadingComment(commentedProp, SyntaxKind.SingleLineCommentTrivia, " only on a", true, false); + emitContext.addSyntheticLeadingComment(commentedProp, SyntaxKind.SingleLineCommentTrivia, " only on a", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); // Both members are part of the same printed tree. The comment attached to // `commentedProp` should not leak onto its sibling. @@ -9431,7 +9442,7 @@ export const obj = { m: 1, s: "hi", b: true }; assert(sourceFile); const emitContext = api.printer.createEmitContext(); - emitContext.addSyntheticLeadingComment(sourceFile.statements[0], SyntaxKind.SingleLineCommentTrivia, " printFile honors emitContext", true, false); + emitContext.addSyntheticLeadingComment(sourceFile.statements[0], SyntaxKind.SingleLineCommentTrivia, " printFile honors emitContext", /*hasTrailingNewLine*/ true, /*hasLeadingNewLine*/ false); const text = api.printer.printFile(sourceFile, { emitContext }); assert.match(text, /printFile honors emitContext/); @@ -9467,10 +9478,10 @@ describe("Program - selected file emit", { concurrency }, () => { "/src/b.js", "/src/b.js.map", ]); - const outputFileName = toRootedFilePath("/src/a.js", undefined); + const outputFileName = toRootedFilePath("/src/a.js", /*currentDirectory*/ undefined); assert.equal(result.outputFiles.get(outputFileName)?.sourceFileName, "/src/a.ts"); assert.match(result.outputFiles.get(outputFileName)!.text, /export const a = 1/); - assert.equal(fs.readFile(toRootedFilePath("/src/a.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/src/a.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("getDeclarationEmit forces declarations and declaration maps", () => { @@ -9487,8 +9498,8 @@ describe("Program - selected file emit", { concurrency }, () => { "/src/b.d.ts", "/src/b.d.ts.map", ]); - assert.equal(result.outputFiles.get(toRootedFilePath("/src/a.d.ts", undefined))?.sourceFileName, "/src/a.ts"); - assert.equal(fs.readFile(toRootedFilePath("/src/a.d.ts", undefined)), serverFS.useOS); + assert.equal(result.outputFiles.get(toRootedFilePath("/src/a.d.ts", /*currentDirectory*/ undefined))?.sourceFileName, "/src/a.ts"); + assert.equal(fs.readFile(toRootedFilePath("/src/a.d.ts", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("selected file emit accepts empty arrays", () => { @@ -9513,9 +9524,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("x"), undefined, undefined, createNumericLiteral("1", 0))], + [createVariableDeclaration(createIdentifier("x"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0))], NodeFlags.Const, ), ); @@ -9539,9 +9550,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("y"), undefined, undefined, createNumericLiteral("42", 0))], + [createVariableDeclaration(createIdentifier("y"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("42", 0))], NodeFlags.Const, ), ); @@ -9564,9 +9575,9 @@ describe("LanguageService - formatNodeForInsertion", { concurrency }, () => { const languageService = snapshot.getConfiguredProject("/tsconfig.json")!.languageService; const node = createVariableStatement( - undefined, + /*modifiers*/ undefined, createVariableDeclarationList( - [createVariableDeclaration(createIdentifier("x"), undefined, undefined, createNumericLiteral("1", 0))], + [createVariableDeclaration(createIdentifier("x"), /*exclamationToken*/ undefined, /*type*/ undefined, createNumericLiteral("1", 0))], NodeFlags.Const, ), ); @@ -9796,11 +9807,11 @@ doThing(); using api = spawnAPI(); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); - const project = snapshot.getConfiguredProject("/tsconfig.json")!; + snapshot.getConfiguredProject("/tsconfig.json"); const node = createTypeAliasDeclaration( [createToken(SyntaxKind.ExportKeyword)], createIdentifier("Test"), - undefined, + /*typeParameters*/ undefined, createKeywordTypeNode(SyntaxKind.AnyKeyword), ); @@ -9988,7 +9999,7 @@ describe("Program - diagnostics", { concurrency }, () => { assert.throws(() => getSymbol(configProperty), /Cached source file not found/); assert.throws(() => api.getSymbol(configProperty), /Cached source file not found/); - fs.writeFile!(toRootedFilePath("/tsconfig.base.json", undefined), `{ "compilerOptions": { "strict": false } }`); + fs.writeFile(toRootedFilePath("/tsconfig.base.json", /*currentDirectory*/ undefined), `{ "compilerOptions": { "strict": false } }`); const extendedConfig = project.program.getConfigSourceFile("/tsconfig.base.json"); assert.ok(extendedConfig); assert.equal(extendedConfig.fileName, "/tsconfig.base.json"); @@ -10209,8 +10220,8 @@ describe("getDefaultProjectForFile", { concurrency }, () => { cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), fs: { ...fs, - readFile: path => virtualFileAvailable && path === fileName ? source : fs.readFile!(path), - fileExists: path => virtualFileAvailable && path === fileName ? true : fs.fileExists!(path), + readFile: path => virtualFileAvailable && path === fileName ? source : fs.readFile(path), + fileExists: path => virtualFileAvailable && path === fileName ? true : fs.fileExists(path), }, }); const snapshot = api.createSnapshot({ @@ -10281,7 +10292,7 @@ describe("getDefaultProjectForFile", { concurrency }, () => { assert.equal(sf1.text, `export const foo = 1;`); // Mutate the file and notify only via fileChanges — no follow-up openFiles/closeFiles. - fs.writeFile!(toRootedFilePath("/loose.ts", undefined), `export const foo = 2;`); + fs.writeFile(toRootedFilePath("/loose.ts", /*currentDirectory*/ undefined), `export const foo = 2;`); const snapshot2 = api.createSnapshot({ openFiles: ["/loose.ts"], fileNotifications: { changed: ["/loose.ts"] }, @@ -10394,7 +10405,7 @@ describe("Program - emit", { concurrency }, () => { using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10412,10 +10423,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, `export const x = 1;\n`); assert.strictEqual(dts, `export declare const x: number;\n`); assert.strictEqual(js2, `export const y = 'typescript';\n`); @@ -10427,7 +10438,7 @@ describe("Program - emit", { concurrency }, () => { using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10443,10 +10454,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, serverFS.useOS); assert.strictEqual(dts, `export declare const x: number;\n`); assert.strictEqual(js2, serverFS.useOS); @@ -10458,7 +10469,7 @@ describe("Program - emit", { concurrency }, () => { using api = new API({ cwd: fileURLToPath(new URL("../../../../", import.meta.url).toString()), - fs: fs, + fs, }); const snapshot = api.createSnapshot({ openProjects: ["/tsconfig.json"] }); @@ -10474,10 +10485,10 @@ describe("Program - emit", { concurrency }, () => { fileSystem: undefined, }); - const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", undefined)); - const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", undefined)); - const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", undefined)); - const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", undefined)); + const js = fs.readFile?.(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)); + const dts = fs.readFile?.(toRootedFilePath("/dist/src/index.d.ts", /*currentDirectory*/ undefined)); + const js2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.js", /*currentDirectory*/ undefined)); + const dts2 = fs.readFile?.(toRootedFilePath("/dist/src/testing.d.ts", /*currentDirectory*/ undefined)); assert.strictEqual(js, `export const x = 1;\n`); assert.strictEqual(dts, serverFS.useOS); assert.strictEqual(js2, `export const y = 'typescript';\n`); @@ -10495,7 +10506,7 @@ describe("Program - emit", { concurrency }, () => { "/dist/src/index.d.ts", "/dist/src/testing.d.ts", ]); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("whole-program emit includes option-controlled maps", () => { @@ -10525,8 +10536,8 @@ describe("Program - emit", { concurrency }, () => { "/dist/src/index.d.ts.map", ]), ); - assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.js.map", undefined))); - assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.d.ts.map", undefined))); + assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.js.map", /*currentDirectory*/ undefined))); + assert.ok(fs.fileExists?.(toRootedFilePath("/dist/src/index.d.ts.map", /*currentDirectory*/ undefined))); const js = project.program.emitToString(EmitOnly.OnlyJs); assert.deepEqual([...js.outputFiles.keys()], [ @@ -10560,8 +10571,8 @@ describe("Program - emit", { concurrency }, () => { assert.equal(result.emitSkipped, true); assert.ok(result.diagnostics.some(d => d.code === 1109)); assert.deepEqual(result.emittedFiles, []); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/bad.js", undefined)), serverFS.useOS); - assert.equal(fs.readFile(toRootedFilePath("/dist/src/good.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/bad.js", /*currentDirectory*/ undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/dist/src/good.js", /*currentDirectory*/ undefined)), serverFS.useOS); const stringResult = project.program.emitToString(); assert.equal(stringResult.emitSkipped, true); @@ -10589,7 +10600,7 @@ describe("Program - emit", { concurrency }, () => { emitSkipped: false, outputFiles: new Map(), }); - assert.equal(fs.readFile(toRootedFilePath("/src/index.js", undefined)), serverFS.useOS); + assert.equal(fs.readFile(toRootedFilePath("/src/index.js", /*currentDirectory*/ undefined)), serverFS.useOS); }); test("emit rejects unknown files and invalid emitOnly values", () => { @@ -10843,7 +10854,7 @@ function spawnAPIWithFS( ): { api: API; fs: ReturnType; } { const fs = createVirtualFileSystem(files); if (onWrite) { - const writeFile = fs.writeFile!; + const writeFile = fs.writeFile; fs.writeFile = (path, content) => { onWrite(path); writeFile(path, content); diff --git a/packages/typescript/test/sync/ast.bench.ts b/packages/typescript/test/sync/ast.bench.ts index 61b811abe1b19..85f22f6eba9f8 100644 --- a/packages/typescript/test/sync/ast.bench.ts +++ b/packages/typescript/test/sync/ast.bench.ts @@ -212,7 +212,8 @@ export function runBenchmarks(options?: { filter?: string; singleIteration?: boo bench.runSync(); for (const task of bench.tasks) { - if (task.result && "error" in task.result) throw task.result.error; + const error = (task.result as { error?: unknown; } | undefined)?.error; + if (error) throw error; } console.table(bench.table()); } diff --git a/packages/typescript/test/sync/ast.test.ts b/packages/typescript/test/sync/ast.test.ts index e71ee4b0847d4..0f8a58926322a 100644 --- a/packages/typescript/test/sync/ast.test.ts +++ b/packages/typescript/test/sync/ast.test.ts @@ -1,6 +1,5 @@ import type { BinaryExpression, - BindingElement, CallExpression, ClassDeclaration, ClassElement, @@ -58,7 +57,6 @@ import { createMissingDeclaration, createNodeArray, createNumericLiteral, - createSourceFile, createStringLiteral, createToken, } from "@typescript/typescript/ast/factory"; @@ -117,8 +115,8 @@ test("index signatures allow an omitted type", () => { const signature = declaration.members[0]; assert.ok(astModule.isIndexSignatureDeclaration(signature)); const type: astModule.TypeNode | undefined = signature.type; - assert.strictEqual(type, undefined); - assert.strictEqual(createIndexSignatureDeclaration(undefined, signature.parameters).type, undefined); + assert.strictEqual(type, /*expected*/ undefined); + assert.strictEqual(createIndexSignatureDeclaration(/*modifiers*/ undefined, signature.parameters).type, /*expected*/ undefined); assert.strictEqual(declaration.members.length, 2); }); @@ -267,7 +265,7 @@ function f() {} assert.strictEqual(result?.kind, SyntaxKind.JSDocReturnTag); assert.strictEqual(visitEachChild(signature, node => node), signature); - const template = factory.createJSDocTemplateTag(factory.createIdentifier("template"), undefined, []); + const template = factory.createJSDocTemplateTag(factory.createIdentifier("template"), /*constraint*/ undefined, []); const typeParameters: readonly astModule.JSDocTemplateTag[] = [template]; const synthesized = factory.createJSDocSignature(typeParameters, parameters, result); const clone = getSynthesizedDeepClone(synthesized); @@ -327,7 +325,7 @@ function f() {} using api = spawnAPI(); const seen: Record = {}; function walk(node: Node): void { - if (astModule.isDefaultClause(node)) assert.strictEqual(Reflect.get(node, "expression"), undefined); + if (astModule.isDefaultClause(node)) assert.strictEqual((node as { expression?: unknown; }).expression, /*expected*/ undefined); if (astModule.isExportAssignment(node)) seen.exportType = node.type; if (astModule.isPropertyAssignment(node)) seen.propertyType = node.type; if (astModule.isShorthandPropertyAssignment(node)) seen.shorthandType = node.type; @@ -364,7 +362,7 @@ function f() {} ); assert.deepStrictEqual(Object.keys(seen).sort(), Object.keys(absent).sort()); for (const name of Object.keys(absent)) { - assert.strictEqual(seen[name] === undefined, true, name); + assert.strictEqual(seen[name] === undefined, /*expected*/ true, name); } }); @@ -381,12 +379,12 @@ function f() {} assert.strictEqual(remoteToken.kind, SyntaxKind.EqualsGreaterThanToken); const body = factory.createBlock([]); - const local = factory.createArrowFunction(undefined, undefined, [], undefined, undefined, body); + const local = factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, /*equalsGreaterThanToken*/ undefined, body); const localToken: astModule.EqualsGreaterThanToken = local.equalsGreaterThanToken; assert.strictEqual(localToken.kind, SyntaxKind.EqualsGreaterThanToken); assert.strictEqual(cloneNode(local).equalsGreaterThanToken, local.equalsGreaterThanToken); const explicitToken = factory.createToken(SyntaxKind.EqualsGreaterThanToken); - const explicit = factory.createArrowFunction(undefined, undefined, [], undefined, explicitToken, body); + const explicit = factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, explicitToken, body); assert.strictEqual(explicit.equalsGreaterThanToken, explicitToken); }); @@ -453,9 +451,9 @@ function f() {} assert.strictEqual(factory.createExportDeclaration().modifierFlags, ModifierFlags.None); const declaration = factory.createFunctionDeclaration( [factory.createToken(SyntaxKind.ExportKeyword), factory.createToken(SyntaxKind.AsyncKeyword)], - undefined, + /*asteriskToken*/ undefined, factory.createIdentifier("f"), - undefined, + /*typeParameters*/ undefined, [], ); assert.strictEqual(declaration.modifierFlags, ModifierFlags.Export | ModifierFlags.Async); @@ -463,33 +461,33 @@ function f() {} }); test("factory scalar accessors preserve explicit values", () => { - assert.strictEqual(factory.createBlock([], true).multiLine, true); - assert.strictEqual(factory.createArrayLiteralExpression([], true).multiLine, true); - assert.strictEqual(factory.createObjectLiteralExpression([], true).multiLine, true); - assert.strictEqual(factory.createImportAttributes(SyntaxKind.WithKeyword, [], true).multiLine, true); - assert.strictEqual(factory.createJsxText(" ", true).containsOnlyTriviaWhiteSpaces, true); - assert.strictEqual(factory.createJSDocTypeLiteral(undefined, true).isArrayType, true); - assert.strictEqual(factory.createExportDeclaration(undefined, true).isTypeOnly, true); - assert.strictEqual(factory.createSyntheticExpression(factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword), true).isSpread, true); + assert.strictEqual(factory.createBlock([], /*multiLine*/ true).multiLine, /*expected*/ true); + assert.strictEqual(factory.createArrayLiteralExpression([], /*multiLine*/ true).multiLine, /*expected*/ true); + assert.strictEqual(factory.createObjectLiteralExpression([], /*multiLine*/ true).multiLine, /*expected*/ true); + assert.strictEqual(factory.createImportAttributes(SyntaxKind.WithKeyword, [], /*multiLine*/ true).multiLine, /*expected*/ true); + assert.strictEqual(factory.createJsxText(" ", /*containsOnlyTriviaWhiteSpaces*/ true).containsOnlyTriviaWhiteSpaces, /*expected*/ true); + assert.strictEqual(factory.createJSDocTypeLiteral(/*jsdocPropertyTags*/ undefined, /*isArrayType*/ true).isArrayType, /*expected*/ true); + assert.strictEqual(factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ true).isTypeOnly, /*expected*/ true); + assert.strictEqual(factory.createSyntheticExpression(factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword), /*isSpread*/ true).isSpread, /*expected*/ true); }); test("optional factory children survive cloning and visiting", () => { const name = factory.createIdentifier("p"); - const property = factory.createPropertySignatureDeclaration(undefined, name); - assert.strictEqual(property.type, undefined); - assert.strictEqual(property.initializer, undefined); + const property = factory.createPropertySignatureDeclaration(/*modifiers*/ undefined, name); + assert.strictEqual(property.type, /*expected*/ undefined); + assert.strictEqual(property.initializer, /*expected*/ undefined); assert.deepStrictEqual(collectKinds(getSynthesizedDeepClone(property)), [SyntaxKind.PropertySignature, SyntaxKind.Identifier]); const clause = factory.createDefaultClause([]); const hasExpression: "expression" extends keyof astModule.DefaultClause ? true : false = false; - assert.strictEqual(hasExpression, false); - assert.strictEqual(Reflect.get(clause, "expression"), undefined); + assert.strictEqual(hasExpression, /*expected*/ false); + assert.strictEqual((clause as { expression?: unknown; }).expression, /*expected*/ undefined); assert.deepStrictEqual([...clause.childrenIter()], []); assert.strictEqual(visitEachChild(clause, node => node), clause); const type = factory.createKeywordTypeNode(SyntaxKind.StringKeyword); const initializer = factory.createStringLiteral("value", TokenFlags.None); - const populated = factory.createPropertySignatureDeclaration(undefined, name, undefined, type, initializer); + const populated = factory.createPropertySignatureDeclaration(/*modifiers*/ undefined, name, /*postfixToken*/ undefined, type, initializer); assert.deepStrictEqual(collectKinds(getSynthesizedDeepClone(populated)), [ SyntaxKind.PropertySignature, SyntaxKind.Identifier, @@ -549,7 +547,7 @@ describe("cloneNode", { concurrency }, () => { const left = createIdentifier("a"); const right = createIdentifier("b"); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const clone = cloneNode(bin); assert.notStrictEqual(clone, bin); @@ -561,7 +559,7 @@ describe("cloneNode", { concurrency }, () => { test("clone has no parent", () => { const id = createIdentifier("x"); const clone = cloneNode(id); - assert.strictEqual(clone.parent, undefined); + assert.strictEqual(clone.parent, /*expected*/ undefined); }); test("clones a token", () => { @@ -581,7 +579,7 @@ describe("visitNode", { concurrency }, () => { test("returns undefined for undefined input", () => { const nothing: Node | undefined = undefined; const result = visitNode(nothing, () => undefined); - assert.strictEqual(result, undefined); + assert.strictEqual(result, /*expected*/ undefined); }); test("returns visitor result", () => { @@ -594,7 +592,7 @@ describe("visitNode", { concurrency }, () => { test("visitor can return undefined to remove node", () => { const id = createIdentifier("x"); const result = visitNode(id, () => undefined); - assert.strictEqual(result, undefined); + assert.strictEqual(result, /*expected*/ undefined); }); }); @@ -602,7 +600,7 @@ describe("visitNodes", { concurrency }, () => { test("returns undefined for undefined input", () => { const nothing: NodeArray | undefined = undefined; const result = visitNodes(nothing, () => undefined); - assert.strictEqual(result, undefined); + assert.strictEqual(result, /*expected*/ undefined); }); test("returns same array if nothing changed", () => { @@ -648,7 +646,7 @@ describe("visitEachChild", { concurrency }, () => { const left = createIdentifier("a"); const right = createIdentifier("b"); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const result = visitEachChild(bin, node => node); assert.strictEqual(result, bin); @@ -657,14 +655,14 @@ describe("visitEachChild", { concurrency }, () => { test("returns undefined for undefined input", () => { const nothing: Node | undefined = undefined; const result = visitEachChild(nothing, node => node); - assert.strictEqual(result, undefined); + assert.strictEqual(result, /*expected*/ undefined); }); test("creates new node when child changes", () => { const left = createIdentifier("a"); const right = createIdentifier("b"); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const newRight = createIdentifier("c"); const result = visitEachChild(bin, node => { @@ -681,7 +679,7 @@ describe("visitEachChild", { concurrency }, () => { test("works on if statement with optional else", () => { const cond = createIdentifier("ok"); const thenBranch = createBlock([]); - const ifStmt = createIfStatement(cond, thenBranch, undefined); + const ifStmt = createIfStatement(cond, thenBranch, /*elseStatement*/ undefined); const newCond = createIdentifier("notOk"); const result = visitEachChild(ifStmt, node => { @@ -692,7 +690,7 @@ describe("visitEachChild", { concurrency }, () => { assert.notStrictEqual(result, ifStmt); assert.strictEqual(result.expression, newCond); assert.strictEqual(result.thenStatement, thenBranch); - assert.strictEqual(result.elseStatement, undefined); + assert.strictEqual(result.elseStatement, /*expected*/ undefined); }); test("works on nodes with NodeArray children", () => { @@ -752,7 +750,7 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { const left = createIdentifier("a"); const right = createNumericLiteral("42", TokenFlags.None); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const clone = getSynthesizedDeepClone(bin); @@ -777,7 +775,7 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { const left = createIdentifier("a"); const right = createIdentifier("b"); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const clone = getSynthesizedDeepClone(bin); @@ -787,14 +785,14 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { }); test("returns undefined for undefined input", () => { - const result = getSynthesizedDeepClone(undefined); - assert.strictEqual(result, undefined); + const result = getSynthesizedDeepClone(/*node*/ undefined); + assert.strictEqual(result, /*expected*/ undefined); }); test("deeply clones if statement with optional else", () => { const cond = createIdentifier("ok"); const thenBlock = createBlock([]); - const ifStmt = createIfStatement(cond, thenBlock, undefined); + const ifStmt = createIfStatement(cond, thenBlock, /*elseStatement*/ undefined); const clone = getSynthesizedDeepClone(ifStmt); @@ -804,7 +802,7 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { assert.strictEqual(clone.expression.kind, SyntaxKind.Identifier); assert.notStrictEqual(clone.thenStatement, thenBlock); assert.strictEqual(clone.thenStatement.kind, SyntaxKind.Block); - assert.strictEqual(clone.elseStatement, undefined); + assert.strictEqual(clone.elseStatement, /*expected*/ undefined); }); test("preserves tree structure with nested children", () => { @@ -849,7 +847,7 @@ describe("getSynthesizedDeepClone", { concurrency }, () => { const left = createIdentifier("x"); const right = createNumericLiteral("1", TokenFlags.None); const op = createToken(SyntaxKind.PlusToken); - const bin = createBinaryExpression(undefined, left, undefined, op, right); + const bin = createBinaryExpression(/*modifiers*/ undefined, left, /*type*/ undefined, op, right); const stmt = createExpressionStatement(bin); const clone = getSynthesizedDeepClone(stmt); @@ -878,8 +876,8 @@ describe("getSynthesizedDeepClones", { concurrency }, () => { }); test("returns undefined for undefined input", () => { - const result = getSynthesizedDeepClones(undefined); - assert.strictEqual(result, undefined); + const result = getSynthesizedDeepClones(/*nodes*/ undefined); + assert.strictEqual(result, /*expected*/ undefined); }); test("preserves pos and end on NodeArray", () => { @@ -1049,11 +1047,11 @@ describe("declaration utilities", { concurrency }, () => { test("getCombinedModifierFlags includes modifiers on factory nodes", () => { const declaration = createFunctionDeclaration( [createToken(SyntaxKind.ExportKeyword), createToken(SyntaxKind.AsyncKeyword)], - undefined, + /*asteriskToken*/ undefined, createIdentifier("f"), - undefined, + /*typeParameters*/ undefined, [], - undefined, + /*type*/ undefined, createBlock([]), ); @@ -1071,7 +1069,7 @@ describe("declaration utilities", { concurrency }, () => { const sf = getRemoteSourceFile(api, "/tsconfig.json", "/src/index.ts"); const statement = sf.statements[0] as VariableStatement; const declaration = statement.declarationList.declarations[0]; - const binding = (declaration.name as ObjectBindingPattern).elements[0] as BindingElement; + const binding = (declaration.name as ObjectBindingPattern).elements[0]; assert.strictEqual( getCombinedModifierFlags(binding), @@ -1116,7 +1114,7 @@ export default declared; assert.strictEqual(getNameOfDeclaration(sf.statements[0] as FunctionDeclaration)?.getText(), "declared"); assert.strictEqual(getNameOfDeclaration(classExpression)?.getText(), "assigned"); assert.strictEqual(getNameOfDeclaration(sf.statements[2] as ExportAssignment)?.getText(), "declared"); - assert.strictEqual(getNameOfDeclaration(undefined), undefined); + assert.strictEqual(getNameOfDeclaration(/*declaration*/ undefined), /*expected*/ undefined); }); test("getNameOfDeclaration returns JavaScript assignment declaration names", () => { @@ -1158,7 +1156,7 @@ export const x = 1;`, assert.ok(typeof comment !== "string"); const link = comment?.[1]; assert.ok(link && isJSDocLink(link)); - assert.strictEqual(link.name, undefined); + assert.strictEqual(link.name, /*expected*/ undefined); } finally { api.close(); @@ -1250,7 +1248,7 @@ interface I extends Parent {} const clone = cloneNode(fooName); assert.strictEqual(clone.kind, SyntaxKind.Identifier); - assert.strictEqual((clone as Identifier).text, "foo"); + assert.strictEqual(clone.text, "foo"); } finally { api.close(); @@ -1714,8 +1712,8 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { const ifToken = stmt.getFirstToken()!; assert.strictEqual(ifToken.getChildCount(), 0); assert.deepStrictEqual(ifToken.getChildren(), []); - assert.strictEqual(ifToken.getFirstToken(), undefined); - assert.strictEqual(ifToken.getLastToken(), undefined); + assert.strictEqual(ifToken.getFirstToken(), /*expected*/ undefined); + assert.strictEqual(ifToken.getLastToken(), /*expected*/ undefined); }); }); @@ -1725,7 +1723,7 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { assert.ok(arr, "expected an array literal"); const list = arr.getChildren().find(c => c.kind === SyntaxKind.SyntaxList); assert.ok(list, "array literal children should include a SyntaxList"); - assert.deepStrictEqual(list!.getChildren().map(c => c.getText()), ["1", ",", "2", ",", "3"]); + assert.deepStrictEqual(list.getChildren().map(c => c.getText()), ["1", ",", "2", ",", "3"]); }); }); @@ -1832,7 +1830,7 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { for (let i = 0; i < children.length; i++) { assert.strictEqual(node.getChildAt(i, sf), children[i]); } - assert.strictEqual(node.getChildAt(children.length, sf), undefined); + assert.strictEqual(node.getChildAt(children.length, sf), /*expected*/ undefined); assert.strictEqual(node.getChildren(sf), children, "getChildren should be cached"); // JSDoc nodes don't synthesize tokens, so the token/tiling invariants don't apply. @@ -1888,6 +1886,7 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { "export function greet(name: string, count = 1): string {", " const parts: string[] = [];", " for (let i = 0; i < count; i++) {", + // eslint-disable-next-line no-template-curly-in-string -- This string is TypeScript source. " parts.push(`hi ${name}`);", " }", " if (parts.length) {", @@ -1903,7 +1902,7 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { // Representative constructs, each exercising a distinct structural path of getChildren // (token synthesis, SyntaxList wrapping, empty lists, decorator lists, JSDoc, JSX, nesting). - const corpus: Array<{ name: string; source: string; jsx?: boolean; js?: boolean; }> = [ + const corpus: { name: string; source: string; jsx?: boolean; js?: boolean; }[] = [ { name: "variable declarations", source: "const a = 1; let b: number = 2; var c, d = 3;" }, { name: "function with optional, default and rest params", source: "function f(a: number, b?: string, c = 1, ...d: any[]): void {}" }, { name: "class with members", source: "class C { x = 1; #y = 2; static s = 3; readonly r: string; constructor(public p: number) {} m() {} get g() { return 1; } set v(x) {} static {} }" }, @@ -1916,6 +1915,7 @@ describe("RemoteNode + child/token getters", { concurrency }, () => { { name: "for variants", source: "for (let i = 0; i < n; i++) {} for (const k in o) {} for (const v of a) {} for (;;) { break; }" }, { name: "switch with an empty case clause", source: "switch (x) { case 1: y(); break; case 2: case 3: z(); default: w(); }" }, { name: "object literal with all member kinds", source: "const o = { a: 1, b, [c]: 2, ...d, m() {}, get g() { return 1; }, set s(v) {}, async am() {}, *gm() {} };" }, + // eslint-disable-next-line no-template-curly-in-string -- This string is TypeScript source. { name: "tagged and nested template literals", source: "const r = tag`a${b}c${`inner${d}`}e`;" }, { name: "comments and jsdoc with tags", source: "// line\n/* block */\n/**\n * @param a the a\n * @returns nothing\n */\nfunction f(a: number) {} // trailing" }, { name: "empty constructs", source: "function f() {} class C {} interface I {} enum E {} { } ; namespace N {}" }, @@ -2021,9 +2021,9 @@ describe("getChildren scanner reuse", { concurrency }, () => { assert.strictEqual(scanner.getToken(), SyntaxKind.Unknown); assert.strictEqual(scanner.getTokenFullStart(), 0); assert.strictEqual(scanner.getTokenEnd(), 0); - assert.strictEqual(scanner.getTokenValue(), undefined); + assert.strictEqual(scanner.getTokenValue(), /*expected*/ undefined); assert.strictEqual(scanner.getTokenFlags(), TokenFlags.None); - assert.strictEqual(scanner.getCommentDirectives(), undefined); + assert.strictEqual(scanner.getCommentDirectives(), /*expected*/ undefined); } const sample = [ diff --git a/packages/typescript/test/sync/astnav.test.ts b/packages/typescript/test/sync/astnav.test.ts index 23fbb4889d156..09a81aebb40ad 100644 --- a/packages/typescript/test/sync/astnav.test.ts +++ b/packages/typescript/test/sync/astnav.test.ts @@ -76,7 +76,7 @@ function toTokenInfo(node: Node): { kind: string; pos: number; end: number; } { // Test configuration // --------------------------------------------------------------------------- -const repoRoot = resolve(import.meta.dirname!, "..", "..", "..", ".."); +const repoRoot = resolve(import.meta.dirname, "..", "..", "..", ".."); const testFile = resolve(repoRoot, "tsc/testdata/fixtures/services/mapCode.ts"); const baselineDir = resolve(repoRoot, "tsc/testdata/baselines/reference/astnav"); diff --git a/packages/typescript/test/sync/shutdown.test.ts b/packages/typescript/test/sync/shutdown.test.ts index 91630c9477688..9faaf1e6fcf7f 100644 --- a/packages/typescript/test/sync/shutdown.test.ts +++ b/packages/typescript/test/sync/shutdown.test.ts @@ -17,6 +17,7 @@ test("close shuts down the API process cleanly", async () => { } }); +// eslint-disable-next-line no-restricted-syntax -- Node reports a null exit code when a process is killed by a signal. function runNode(script: string): Promise<{ status: number | null; stderr: string; }> { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [ diff --git a/packages/typescript/test/sync/timing.test.ts b/packages/typescript/test/sync/timing.test.ts index 7a6d0b93b59fa..94afcfefcfea7 100644 --- a/packages/typescript/test/sync/timing.test.ts +++ b/packages/typescript/test/sync/timing.test.ts @@ -22,7 +22,7 @@ describe("sync IPC timing", () => { nested = true; api.parseCommandLine([nestedArgument]); } - return fs.readFile!(path); + return fs.readFile(path); }, }, }); diff --git a/packages/typescript/test/sync/transport.test.ts b/packages/typescript/test/sync/transport.test.ts index 35d8bb926f839..70cda322d7db0 100644 --- a/packages/typescript/test/sync/transport.test.ts +++ b/packages/typescript/test/sync/transport.test.ts @@ -81,6 +81,6 @@ describe("sync transport", () => { assert.deepStrictEqual(methods, ["initialize", "parseCommandLine", "batchRequests"]); assert.strictEqual(batchParams?.maxResponseBytesPerPage, 1); api.close(); - assert.strictEqual(closed, true); + assert.strictEqual(closed, /*expected*/ true); }); }); diff --git a/packages/typescript/test/sync/wasm.test.ts b/packages/typescript/test/sync/wasm.test.ts index afcfa08fdff7e..0a7fb4730a35c 100644 --- a/packages/typescript/test/sync/wasm.test.ts +++ b/packages/typescript/test/sync/wasm.test.ts @@ -152,8 +152,10 @@ describe("API over WebAssembly", () => { } const output = await readFile(stdoutPath, "utf8"); assert.strictEqual(exitCode, 0, `tsc -p ${project} failed:\n${output}`); + const outputFiles = output.trim().split("\n"); + outputFiles.sort(); assert.deepStrictEqual( - output.trim().split("\n").sort(), + outputFiles, [`${project}/index.ts`, `${project}/node_modules/pkg/index.d.ts`], ); } @@ -191,7 +193,7 @@ describe("API over WebAssembly", () => { stdio: ["pipe", "pipe", "pipe"], }); t.after(() => { - if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + if (child.exitCode == undefined && child.signalCode == undefined) child.kill("SIGKILL"); }); let stdout = Buffer.alloc(0); let stderr = ""; @@ -210,14 +212,15 @@ describe("API over WebAssembly", () => { if (stdout.length < bodyStart + length) return; const message = JSON.parse(stdout.subarray(bodyStart, bodyStart + length).toString()); stdout = stdout.subarray(bodyStart + length); - if (!("method" in message)) responses.add(message.id); - else if ("id" in message) send({ id: message.id, result: null }); + if (!message.method) responses.add(message.id); + // eslint-disable-next-line no-restricted-syntax -- JSON-RPC responses require a result. + else if (message.id != undefined) send({ id: message.id, result: null }); } }); child.stderr.setEncoding("utf8"); child.stderr.on("data", chunk => stderr += chunk); const waitForResponse = async (id: number) => { - while (!responses.has(id) && child.exitCode === null && !t.signal.aborted) { + while (!responses.has(id) && child.exitCode == undefined && !t.signal.aborted) { await new Promise(resolve => setTimeout(resolve, 10)); } assert.ok(responses.has(id), `no response to request ${id}\n${stderr}`); @@ -229,9 +232,12 @@ describe("API over WebAssembly", () => { id: 1, method: "initialize", params: { + // eslint-disable-next-line no-restricted-syntax -- LSP permits a null process ID. processId: null, capabilities: {}, + // eslint-disable-next-line no-restricted-syntax -- LSP requires null for an absent root URI. rootUri: null, + // eslint-disable-next-line no-restricted-syntax -- Null means no workspace folders are configured. workspaceFolders: null, }, }); @@ -241,6 +247,7 @@ describe("API over WebAssembly", () => { send({ id: 2, method: "shutdown" }); await waitForResponse(2); child.stdin.end(); + // eslint-disable-next-line no-restricted-syntax -- Node reports a null exit code when a process is killed by a signal. const exitCode = child.exitCode ?? await new Promise(resolve => child.once("exit", resolve)); assert.strictEqual(exitCode, 0, stderr); }); @@ -273,7 +280,7 @@ describe("API over WebAssembly", () => { stdio: ["pipe", "pipe", "pipe"], }); t.after(() => { - if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + if (child.exitCode == undefined && child.signalCode == undefined) child.kill("SIGKILL"); }); let stderr = ""; child.stderr.setEncoding("utf8"); @@ -281,6 +288,7 @@ describe("API over WebAssembly", () => { await new Promise(resolve => setTimeout(resolve, 250)); child.stdin.end(); + // eslint-disable-next-line no-restricted-syntax -- Node reports a null exit code when a process is killed by a signal. const exitCode = child.exitCode ?? await new Promise(resolve => child.once("exit", resolve)); assert.strictEqual(exitCode, 0, stderr); }); diff --git a/packages/typescript/test/testUtils.ts b/packages/typescript/test/testUtils.ts index 7dc2ce71e0b26..b74295b7b5755 100644 --- a/packages/typescript/test/testUtils.ts +++ b/packages/typescript/test/testUtils.ts @@ -51,7 +51,8 @@ function createVDirectory(name: string): VDirectory { return { type: "directory", name, - children: Object.create(null) as Record, + // eslint-disable-next-line no-restricted-syntax -- Directory entries need a null-prototype dictionary. + children: Object.create(/*o*/ null) as Record, }; } @@ -64,7 +65,7 @@ export function createVirtualFileSystem( const content = new Map(); for (const [rawFilePath, data] of Object.entries(files)) { - const filePath = toRootedFilePath(rawFilePath, undefined); + const filePath = toRootedFilePath(rawFilePath, /*currentDirectory*/ undefined); const key = getKey(filePath); if (content.has(key)) { throw new Error(`Duplicate virtual filesystem path: ${filePath}`); @@ -124,7 +125,7 @@ export function createVirtualFileSystem( else if (current.children[key].type !== "directory") { throw new Error(`Cannot create directory: a file already exists at "/${segments.join("/")}"`); } - current = current.children[key] as VDirectory; + current = current.children[key]; } return current; } diff --git a/packages/typescript/test/wasm.ts b/packages/typescript/test/wasm.ts index 9fcc094f3c7a2..d66c68908090d 100644 --- a/packages/typescript/test/wasm.ts +++ b/packages/typescript/test/wasm.ts @@ -58,7 +58,7 @@ class TestWasmTransport extends WasmTransport { } /** The disk a native server process would use for `serverFS.useOS`. */ -const diskFileSystem: { [K in keyof FileSystemCallbacks]: Extract; } = { +const diskFileSystem: { [K in keyof FileSystemCallbacks]: Extract unknown>; } = { directoryExists: path => statSync(path, { throwIfNoEntry: false })?.isDirectory() ?? false, fileExists: path => statSync(path, { throwIfNoEntry: false })?.isFile() ?? false, getAccessibleEntries: path => { @@ -149,8 +149,8 @@ function createWasmAPIOptions(options: WasmAPIOptions): WasmAPIOptions { }; } -export function withWasm(API: T): T { - return new Proxy(API, { +export function withWasm(apiClass: T): T { + return new Proxy(apiClass, { construct(target, args) { return Reflect.construct(target, [createWasmAPIOptions(args[0] ?? {})]); }, From 979ad3f1583b95b80c7157ebd6c58cda4310ed46 Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Mon, 23 Nov 2026 18:02:09 -0800 Subject: [PATCH 3/3] Fix review findings --- Herebyfile.mjs | 13 +++++++++++-- .../rules/no-array-mutating-method-expressions.cjs | 2 +- packages/typescript/eslint/rules/no-keywords.cjs | 13 ++++++------- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Herebyfile.mjs b/Herebyfile.mjs index a710e35331efd..831bd157863e0 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -1431,15 +1431,24 @@ const customLinterTool = createCachedTool({ }, }); +// ESLint runs the local compiler, which can't execute when GOOS/GOARCH target another platform. +const lintTypeScriptOnHost = (!process.env.GOOS || process.env.GOOS === nodeToGOOS(process.platform)) + && (!process.env.GOARCH || process.env.GOARCH === nodeToGOARCH(process.arch, process.platform)); + export const lint = task({ name: "lint", description: "Runs Go and TypeScript linters.", - dependencies: [local, buildAPI], + dependencies: lintTypeScriptOnHost ? [local, buildAPI] : [], run: runLint, }); async function runLint() { - await runLintTypeScript(); + if (lintTypeScriptOnHost) { + await runLintTypeScript(); + } + else { + console.log("Skipping TypeScript lint for non-host GOOS/GOARCH"); + } const lintArgs = ["run"]; if (defaultGoBuildTags.length) { lintArgs.push("--build-tags", defaultGoBuildTags.join(",")); diff --git a/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs b/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs index 54c87497a6a9a..c6f7a41cb8d96 100644 --- a/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs +++ b/packages/typescript/eslint/rules/no-array-mutating-method-expressions.cjs @@ -118,7 +118,7 @@ module.exports = createRule({ return Object.fromEntries( Object.entries(mutatingMethods).map(([method, toMethod]) => [ - `CallExpression > MemberExpression[property.name='${method}'][computed=false]`, + `CallExpression > MemberExpression.callee[property.name='${method}'][computed=false]`, node => check(node, method, toMethod), ]), ); diff --git a/packages/typescript/eslint/rules/no-keywords.cjs b/packages/typescript/eslint/rules/no-keywords.cjs index 668d059ac993e..a50714a9568c4 100644 --- a/packages/typescript/eslint/rules/no-keywords.cjs +++ b/packages/typescript/eslint/rules/no-keywords.cjs @@ -48,13 +48,12 @@ module.exports = createRule({ /** @type {(node: TSESTree.ObjectPattern) => void} */ const checkProperties = node => { node.properties.forEach(property => { - if ( - property && - property.type === AST_NODE_TYPES.Property && - property.key.type === AST_NODE_TYPES.Identifier && - isKeyword(property.key.name) - ) { - report(property.key); + if (property.type !== AST_NODE_TYPES.Property) { + return; + } + const binding = property.value.type === AST_NODE_TYPES.AssignmentPattern ? property.value.left : property.value; + if (binding.type === AST_NODE_TYPES.Identifier && isKeyword(binding.name)) { + report(binding); } }); };