diff options
author | Kitson Kelly <me@kitsonkelly.com> | 2022-03-02 07:44:43 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-03-02 07:44:43 +1100 |
commit | 7fc5bfe51b7d405aaa5293ec6f1a8f1e9119aea2 (patch) | |
tree | 440bd7c939407adc69bedfb678ee16538353073e /cli/tsc | |
parent | 4be0365fb8251a8614f16e6162f4f43c9885d2a3 (diff) |
feat(cli): update to TypeScript 4.6.2 (#13474)
Diffstat (limited to 'cli/tsc')
-rw-r--r-- | cli/tsc/00_typescript.js | 7085 |
1 files changed, 4459 insertions, 2626 deletions
diff --git a/cli/tsc/00_typescript.js b/cli/tsc/00_typescript.js index e350e2e0b..e239cb79e 100644 --- a/cli/tsc/00_typescript.js +++ b/cli/tsc/00_typescript.js @@ -290,11 +290,11 @@ var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. - ts.versionMajorMinor = "4.5"; + ts.versionMajorMinor = "4.6"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types - ts.version = "4.5.2"; + ts.version = "4.6.2"; /* @internal */ var Comparison; (function (Comparison) { @@ -305,13 +305,18 @@ var ts; /* @internal */ var NativeCollections; (function (NativeCollections) { + var globals = typeof globalThis !== "undefined" ? globalThis : + typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + undefined; /** * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). */ function tryGetNativeMap() { // Internet Explorer's Map doesn't support iteration, so don't use it. + var gMap = globals === null || globals === void 0 ? void 0 : globals.Map; // eslint-disable-next-line no-in-operator - return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined; + return typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined; } NativeCollections.tryGetNativeMap = tryGetNativeMap; /** @@ -319,8 +324,9 @@ var ts; */ function tryGetNativeSet() { // Internet Explorer's Set doesn't support iteration, so don't use it. + var gSet = globals === null || globals === void 0 ? void 0 : globals.Set; // eslint-disable-next-line no-in-operator - return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined; + return typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined; } NativeCollections.tryGetNativeSet = tryGetNativeSet; })(NativeCollections || (NativeCollections = {})); @@ -356,26 +362,6 @@ var ts; ts.emptyArray = []; ts.emptyMap = new ts.Map(); ts.emptySet = new ts.Set(); - function createMap() { - return new ts.Map(); - } - ts.createMap = createMap; - /** - * Create a new map from a template object is provided, the map will copy entries from it. - * @deprecated Use `new Map(getEntries(template))` instead. - */ - function createMapFromTemplate(template) { - var map = new ts.Map(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1057,7 +1043,11 @@ var ts; } return deduplicated; } - function insertSorted(array, insert, compare) { + function createSortedArray() { + return []; // TODO: GH#19873 + } + ts.createSortedArray = createSortedArray; + function insertSorted(array, insert, compare, allowDuplicates) { if (array.length === 0) { array.push(insert); return; @@ -1066,6 +1056,9 @@ var ts; if (insertIndex < 0) { array.splice(~insertIndex, 0, insert); } + else if (allowDuplicates) { + array.splice(insertIndex, 0, insert); + } } ts.insertSorted = insertSorted; function sortAndDeduplicate(array, comparer, equalityComparer) { @@ -1475,11 +1468,11 @@ var ts; return result; } ts.getAllKeys = getAllKeys; - function getOwnValues(sparseArray) { + function getOwnValues(collection) { var values = []; - for (var key in sparseArray) { - if (hasOwnProperty.call(sparseArray, key)) { - values.push(sparseArray[key]); + for (var key in collection) { + if (hasOwnProperty.call(collection, key)) { + values.push(collection[key]); } } return values; @@ -2610,11 +2603,6 @@ var ts; return value; } Debug.checkDefined = checkDefined; - /** - * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether - * a value is defined at the statement level. - */ - Debug.assertDefined = checkDefined; function assertEachIsDefined(value, message, stackCrawlMark) { for (var _i = 0, value_1 = value; _i < value_1.length; _i++) { var v = value_1[_i]; @@ -2627,11 +2615,6 @@ var ts; return value; } Debug.checkEachDefined = checkEachDefined; - /** - * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether - * the elements of an array are defined at the statement level. - */ - Debug.assertEachDefined = checkEachDefined; function assertNever(member, message, stackCrawlMark) { if (message === void 0) { message = "Illegal value:"; } var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member); @@ -4994,6 +4977,7 @@ var ts; NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass"; NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers"; NodeCheckFlags[NodeCheckFlags["ContainsSuperPropertyInStaticInitializer"] = 134217728] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags[NodeCheckFlags["InCheckIdentifier"] = 268435456] = "InCheckIdentifier"; })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); var TypeFlags; (function (TypeFlags) { @@ -5050,6 +5034,8 @@ var ts; TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike"; TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike"; /* @internal */ + TypeFlags[TypeFlags["DefinitelyNonNullable"] = 470302716] = "DefinitelyNonNullable"; + /* @internal */ TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains"; TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection"; TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType"; @@ -5416,6 +5402,7 @@ var ts; ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019"; ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020"; ScriptTarget[ScriptTarget["ES2021"] = 8] = "ES2021"; + ScriptTarget[ScriptTarget["ES2022"] = 9] = "ES2022"; ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext"; ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON"; ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest"; @@ -5584,15 +5571,16 @@ var ts; TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript"; TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx"; TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext"; - TransformFlags[TransformFlags["ContainsES2021"] = 8] = "ContainsES2021"; - TransformFlags[TransformFlags["ContainsES2020"] = 16] = "ContainsES2020"; - TransformFlags[TransformFlags["ContainsES2019"] = 32] = "ContainsES2019"; - TransformFlags[TransformFlags["ContainsES2018"] = 64] = "ContainsES2018"; - TransformFlags[TransformFlags["ContainsES2017"] = 128] = "ContainsES2017"; - TransformFlags[TransformFlags["ContainsES2016"] = 256] = "ContainsES2016"; - TransformFlags[TransformFlags["ContainsES2015"] = 512] = "ContainsES2015"; - TransformFlags[TransformFlags["ContainsGenerator"] = 1024] = "ContainsGenerator"; - TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 2048] = "ContainsDestructuringAssignment"; + TransformFlags[TransformFlags["ContainsES2022"] = 8] = "ContainsES2022"; + TransformFlags[TransformFlags["ContainsES2021"] = 16] = "ContainsES2021"; + TransformFlags[TransformFlags["ContainsES2020"] = 32] = "ContainsES2020"; + TransformFlags[TransformFlags["ContainsES2019"] = 64] = "ContainsES2019"; + TransformFlags[TransformFlags["ContainsES2018"] = 128] = "ContainsES2018"; + TransformFlags[TransformFlags["ContainsES2017"] = 256] = "ContainsES2017"; + TransformFlags[TransformFlags["ContainsES2016"] = 512] = "ContainsES2016"; + TransformFlags[TransformFlags["ContainsES2015"] = 1024] = "ContainsES2015"; + TransformFlags[TransformFlags["ContainsGenerator"] = 2048] = "ContainsGenerator"; + TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 4096] = "ContainsDestructuringAssignment"; // Markers // - Flags used to indicate that a subtree contains a specific transformation. TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 4096] = "ContainsTypeScriptClassSyntax"; @@ -5619,15 +5607,16 @@ var ts; TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript"; TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx"; TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext"; - TransformFlags[TransformFlags["AssertES2021"] = 8] = "AssertES2021"; - TransformFlags[TransformFlags["AssertES2020"] = 16] = "AssertES2020"; - TransformFlags[TransformFlags["AssertES2019"] = 32] = "AssertES2019"; - TransformFlags[TransformFlags["AssertES2018"] = 64] = "AssertES2018"; - TransformFlags[TransformFlags["AssertES2017"] = 128] = "AssertES2017"; - TransformFlags[TransformFlags["AssertES2016"] = 256] = "AssertES2016"; - TransformFlags[TransformFlags["AssertES2015"] = 512] = "AssertES2015"; - TransformFlags[TransformFlags["AssertGenerator"] = 1024] = "AssertGenerator"; - TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 2048] = "AssertDestructuringAssignment"; + TransformFlags[TransformFlags["AssertES2022"] = 8] = "AssertES2022"; + TransformFlags[TransformFlags["AssertES2021"] = 16] = "AssertES2021"; + TransformFlags[TransformFlags["AssertES2020"] = 32] = "AssertES2020"; + TransformFlags[TransformFlags["AssertES2019"] = 64] = "AssertES2019"; + TransformFlags[TransformFlags["AssertES2018"] = 128] = "AssertES2018"; + TransformFlags[TransformFlags["AssertES2017"] = 256] = "AssertES2017"; + TransformFlags[TransformFlags["AssertES2016"] = 512] = "AssertES2016"; + TransformFlags[TransformFlags["AssertES2015"] = 1024] = "AssertES2015"; + TransformFlags[TransformFlags["AssertGenerator"] = 2048] = "AssertGenerator"; + TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 4096] = "AssertDestructuringAssignment"; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. @@ -5931,704 +5920,6 @@ var ts; }, }; })(ts || (ts = {})); -/* @internal */ -var ts; -(function (ts) { - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - ts.altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - //// Path Tests - /** - * Determines whether a charCode corresponds to `/` or `\`. - */ - function isAnyDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } - ts.isAnyDirectorySeparator = isAnyDirectorySeparator; - /** - * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). - */ - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - /** - * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - /** - * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). - * - * ```ts - * // POSIX - * pathIsAbsolute("/path/to/file.ext") === true - * // DOS - * pathIsAbsolute("c:/path/to/file.ext") === true - * // URL - * pathIsAbsolute("file:///path/to/file.ext") === true - * // Non-absolute - * pathIsAbsolute("path/to/file.ext") === false - * pathIsAbsolute("./path/to/file.ext") === false - * ``` - */ - function pathIsAbsolute(path) { - return getEncodedRootLength(path) !== 0; - } - ts.pathIsAbsolute = pathIsAbsolute; - /** - * Determines whether a path starts with a relative path component (i.e. `.` or `..`). - */ - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is neither relative nor absolute, e.g. "path/to/file". - * Also known misleadingly as "non-relative". - */ - function pathIsBareSpecifier(path) { - return !pathIsAbsolute(path) && !pathIsRelative(path); - } - ts.pathIsBareSpecifier = pathIsBareSpecifier; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; - function fileExtensionIs(path, extension) { - return path.length > extension.length && ts.endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - //// Path Parsing - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function getBaseFileName(path, extensions, ignoreCase) { - path = normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") { - return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; - } - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); - if (result) - return result; - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArray([root], rest, true); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - * - * ```ts - * // POSIX - * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] - * getPathComponents("/path/to/") === ["/", "path", "to"] - * getPathComponents("/") === ["/"] - * // DOS - * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] - * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] - * getPathComponents("c:/") === ["c:/"] - * getPathComponents("c:") === ["c:"] - * // URL - * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] - * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] - * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] - * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] - * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] - * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] - * getPathComponents("file://server/") === ["file://server/"] - * getPathComponents("file://server") === ["file://server"] - * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] - * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] - * getPathComponents("file:///") === ["file:///"] - * getPathComponents("file://") === ["file://"] - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = combinePaths(currentDirectory, path); - return pathComponents(path, getRootLength(path)); - } - ts.getPathComponents = getPathComponents; - //// Path Formatting - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - * - * ```ts - * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" - * ``` - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - //// Path Normalization - /** - * Normalize path separators, converting `\` into `/`. - */ - function normalizeSlashes(path) { - var index = path.indexOf("\\"); - if (index === -1) { - return path; - } - backslashRegExp.lastIndex = index; // prime regex with known position - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. - * - * ```ts - * // Non-rooted - * combinePaths("path", "to", "file.ext") === "path/to/file.ext" - * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" - * // POSIX - * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" - * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" - * // DOS - * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" - * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" - * // URL - * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" - * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" - * ``` - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = normalizeSlashes(relativePath); - if (!path || getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. Trailing directory separators are preserved. - * - * ```ts - * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" - * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" - * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" - * ``` - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path)); - } - ts.resolvePath = resolvePath; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - * - * ```ts - * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] - * ``` - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function normalizePath(path) { - path = normalizeSlashes(path); - // Most paths don't require normalization - if (!relativePathSegmentRegExp.test(path)) { - return path; - } - // Some paths only require cleanup of `/./` or leading `./` - var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); - if (simplified !== path) { - path = simplified; - if (!relativePathSegmentRegExp.test(path)) { - return path; - } - } - // Other paths require full normalization - var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); - return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.normalizePath = normalizePath; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = isRootedDiskPath(fileName) - ? normalizePath(fileName) - : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - * - * ```ts - * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" - * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" - * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" - * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" - * ``` - */ - function ensurePathIsNonModuleName(path) { - return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; - //// Path Comparisons - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, getRootLength(a)); - var bRoot = b.substring(0, getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = reducePathComponents(getPathComponents(a)); - var bComponents = reducePathComponents(getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_2 = componentComparer(aComponents[i], bComponents[i]); - if (result_2 !== 0 /* EqualTo */) { - return result_2; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = reducePathComponents(getPathComponents(parent)); - var childComponents = reducePathComponents(getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - /** - * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. - * Comparison is case-sensitive between the canonical paths. - * - * Use `containsPath` if file names are not already reduced and absolute. - */ - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - //// Relative Paths - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = reducePathComponents(getPathComponents(from)); - var toComponents = reducePathComponents(getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArray(__spreadArray([""], relative, true), components, true); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; - function isNodeModulesDirectory(dirPath) { - return ts.endsWith(dirPath, "/node_modules"); - } - ts.isNodeModulesDirectory = isNodeModulesDirectory; -})(ts || (ts = {})); var ts; (function (ts) { /** @@ -7023,11 +6314,15 @@ var ts; ts.getFileWatcherEventKind = getFileWatcherEventKind; /*@internal*/ ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"]; + var curSysLog = ts.noop; // eslint-disable-line prefer-const /*@internal*/ - ts.sysLog = ts.noop; // eslint-disable-line prefer-const + function sysLog(s) { + return curSysLog(s); + } + ts.sysLog = sysLog; /*@internal*/ function setSysLog(logger) { - ts.sysLog = logger; + curSysLog = logger; } ts.setSysLog = setSysLog; /** @@ -7162,7 +6457,7 @@ var ts; } function onTimerToUpdateChildWatches() { timerToUpdateChildWatches = undefined; - ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: ".concat(cacheToUpdateChildWatches.size)); + sysLog("sysLog:: onTimerToUpdateChildWatches:: ".concat(cacheToUpdateChildWatches.size)); var start = ts.timestamp(); var invokeMap = new ts.Map(); while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) { @@ -7175,7 +6470,7 @@ var ts; var hasChanges = updateChildWatches(dirName, dirPath, options); invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames); } - ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: ".concat(ts.timestamp() - start, "ms:: ").concat(cacheToUpdateChildWatches.size)); + sysLog("sysLog:: invokingWatchers:: Elapsed:: ".concat(ts.timestamp() - start, "ms:: ").concat(cacheToUpdateChildWatches.size)); callbackCache.forEach(function (callbacks, rootDirName) { var existing = invokeMap.get(rootDirName); if (existing) { @@ -7191,7 +6486,7 @@ var ts; } }); var elapsed = ts.timestamp() - start; - ts.sysLog("sysLog:: Elapsed:: ".concat(elapsed, "ms:: onTimerToUpdateChildWatches:: ").concat(cacheToUpdateChildWatches.size, " ").concat(timerToUpdateChildWatches)); + sysLog("sysLog:: Elapsed:: ".concat(elapsed, "ms:: onTimerToUpdateChildWatches:: ").concat(cacheToUpdateChildWatches.size, " ").concat(timerToUpdateChildWatches)); } function removeChildWatches(parentWatcher) { if (!parentWatcher) @@ -7778,7 +7073,7 @@ var ts; * @param createWatcher */ function invokeCallbackAndUpdateWatcher(createWatcher) { - ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing watcher to ").concat(createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing", "FileSystemEntryWatcher")); // Call the callback for current directory callback("rename", ""); // If watcher is not closed, update it @@ -7803,7 +7098,7 @@ var ts; } } if (hitSystemWatcherLimit) { - ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Defaulting to fsWatchFile")); return watchPresentFileSystemEntryWithFsWatchFile(); } try { @@ -7819,7 +7114,7 @@ var ts; // Eg. on linux the number of watches are limited and one could easily exhaust watches and the exception ENOSPC is thrown when creating watcher at that point // so instead of throwing error, use fs.watchFile hitSystemWatcherLimit || (hitSystemWatcherLimit = e.code === "ENOSPC"); - ts.sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); + sysLog("sysLog:: ".concat(fileOrDirectory, ":: Changing to fsWatchFile")); return watchPresentFileSystemEntryWithFsWatchFile(); } } @@ -8057,8 +7352,706 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + ts.altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + /** + * Determines whether a path is neither relative nor absolute, e.g. "path/to/file". + * Also known misleadingly as "non-relative". + */ + function pathIsBareSpecifier(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path); + } + ts.pathIsBareSpecifier = pathIsBareSpecifier; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArray([root], rest, true); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + var index = path.indexOf("\\"); + if (index === -1) { + return path; + } + backslashRegExp.lastIndex = index; // prime regex with known position + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths, false)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + * ``` + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + // Most paths don't require normalization + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + // Some paths only require cleanup of `/./` or leading `./` + var simplified = path.replace(/\/\.\//g, "/").replace(/^\.\//, ""); + if (simplified !== path) { + path = simplified; + if (!relativePathSegmentRegExp.test(path)) { + return path; + } + } + // Other paths require full normalization + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_2 = componentComparer(aComponents[i], bComponents[i]); + if (result_2 !== 0 /* EqualTo */) { + return result_2; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * Use `containsPath` if file names are not already reduced and absolute. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArray(__spreadArray([""], relative, true), components, true); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + ts.isNodeModulesDirectory = isNodeModulesDirectory; +})(ts || (ts = {})); // <auto-generated /> -// generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' +// generated from './diagnosticMessages.json' in 'src/compiler' /* @internal */ var ts; (function (ts) { @@ -8150,7 +8143,7 @@ var ts; Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."), A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: diag(1115, ts.DiagnosticCategory.Error, "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115", "A 'continue' statement can only jump to a label of an enclosing iteration statement."), A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: diag(1116, ts.DiagnosticCategory.Error, "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116", "A 'break' statement can only jump to a label of an enclosing statement."), - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode_1117", "An object literal cannot have multiple properties with the same name in strict mode."), + An_object_literal_cannot_have_multiple_properties_with_the_same_name: diag(1117, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_properties_with_the_same_name_1117", "An object literal cannot have multiple properties with the same name."), An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: diag(1118, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name_1118", "An object literal cannot have multiple get/set accessors with the same name."), An_object_literal_cannot_have_property_and_accessor_with_the_same_name: diag(1119, ts.DiagnosticCategory.Error, "An_object_literal_cannot_have_property_and_accessor_with_the_same_name_1119", "An object literal cannot have property and accessor with the same name."), An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."), @@ -8248,10 +8241,10 @@ var ts; A_type_predicate_cannot_reference_a_rest_parameter: diag(1229, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_a_rest_parameter_1229", "A type predicate cannot reference a rest parameter."), A_type_predicate_cannot_reference_element_0_in_a_binding_pattern: diag(1230, ts.DiagnosticCategory.Error, "A_type_predicate_cannot_reference_element_0_in_a_binding_pattern_1230", "A type predicate cannot reference element '{0}' in a binding pattern."), An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration_1231", "An export assignment must be at the top level of a file or module declaration."), - An_import_declaration_can_only_be_used_in_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232", "An import declaration can only be used in a namespace or module."), - An_export_declaration_can_only_be_used_in_a_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_in_a_module_1233", "An export declaration can only be used in a module."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1232, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1232", "An import declaration can only be used at the top level of a namespace or module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module: diag(1233, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module_1233", "An export declaration can only be used at the top level of a namespace or module."), An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file: diag(1234, ts.DiagnosticCategory.Error, "An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file_1234", "An ambient module declaration is only allowed at the top level in a file."), - A_namespace_declaration_is_only_allowed_in_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235", "A namespace declaration is only allowed in a namespace or module."), + A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module: diag(1235, ts.DiagnosticCategory.Error, "A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module_1235", "A namespace declaration is only allowed at the top level of a namespace or module."), The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: diag(1236, ts.DiagnosticCategory.Error, "The_return_type_of_a_property_decorator_function_must_be_either_void_or_any_1236", "The return type of a property decorator function must be either 'void' or 'any'."), The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: diag(1237, ts.DiagnosticCategory.Error, "The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any_1237", "The return type of a parameter decorator function must be either 'void' or 'any'."), Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: diag(1238, ts.DiagnosticCategory.Error, "Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression_1238", "Unable to resolve signature of class decorator when called as an expression."), @@ -8283,6 +8276,9 @@ var ts; An_optional_element_cannot_follow_a_rest_element: diag(1266, ts.DiagnosticCategory.Error, "An_optional_element_cannot_follow_a_rest_element_1266", "An optional element cannot follow a rest element."), Property_0_cannot_have_an_initializer_because_it_is_marked_abstract: diag(1267, ts.DiagnosticCategory.Error, "Property_0_cannot_have_an_initializer_because_it_is_marked_abstract_1267", "Property '{0}' cannot have an initializer because it is marked abstract."), An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type: diag(1268, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_number_symbol_or_a_template_literal_type_1268", "An index signature parameter type must be 'string', 'number', 'symbol', or a template literal type."), + Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided: diag(1269, ts.DiagnosticCategory.Error, "Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided_1269", "Cannot use 'export import' on a type or type-only namespace when the '--isolatedModules' flag is provided."), + Decorator_function_return_type_0_is_not_assignable_to_type_1: diag(1270, ts.DiagnosticCategory.Error, "Decorator_function_return_type_0_is_not_assignable_to_type_1_1270", "Decorator function return type '{0}' is not assignable to type '{1}'."), + Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any: diag(1271, ts.DiagnosticCategory.Error, "Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any_1271", "Decorator function return type is '{0}' but is expected to be 'void' or 'any'."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."), @@ -8297,7 +8293,7 @@ var ts; Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd_system_umd_node12_or_nodenext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_es2022_esnext_commonjs_amd__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12', or 'nodenext'."), - Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext'."), + Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext_1324", "Dynamic imports only support a second argument when the '--module' option is set to 'esnext' or 'nodenext'."), Argument_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Argument_of_dynamic_import_cannot_be_spread_element_1325", "Argument of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."), String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."), @@ -8418,6 +8414,9 @@ var ts; Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression: diag(1451, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member__1451", "Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression"), The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output: diag(1470, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output_1470", "The 'import.meta' meta-property is not allowed in files which will build into CommonJS output."), Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_synchronously_Use_dynamic_import_instead: diag(1471, ts.DiagnosticCategory.Error, "Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_c_1471", "Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead."), + catch_or_finally_expected: diag(1472, ts.DiagnosticCategory.Error, "catch_or_finally_expected_1472", "'catch' or 'finally' expected."), + An_import_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1473, ts.DiagnosticCategory.Error, "An_import_declaration_can_only_be_used_at_the_top_level_of_a_module_1473", "An import declaration can only be used at the top level of a module."), + An_export_declaration_can_only_be_used_at_the_top_level_of_a_module: diag(1474, ts.DiagnosticCategory.Error, "An_export_declaration_can_only_be_used_at_the_top_level_of_a_module_1474", "An export declaration can only be used at the top level of a module."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -8437,6 +8436,7 @@ var ts; Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambiguity: diag(2308, ts.DiagnosticCategory.Error, "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308", "Module {0} has already exported a member named '{1}'. Consider explicitly re-exporting to resolve the ambiguity."), An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: diag(2309, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309", "An export assignment cannot be used in a module with other exported elements."), Type_0_recursively_references_itself_as_a_base_type: diag(2310, ts.DiagnosticCategory.Error, "Type_0_recursively_references_itself_as_a_base_type_2310", "Type '{0}' recursively references itself as a base type."), + Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function: diag(2311, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function_2311", "Cannot find name '{0}'. Did you mean to write this in an async function?"), An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2312, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_me_2312", "An interface can only extend an object type or intersection of object types with statically known members."), Type_parameter_0_has_a_circular_constraint: diag(2313, ts.DiagnosticCategory.Error, "Type_parameter_0_has_a_circular_constraint_2313", "Type parameter '{0}' has a circular constraint."), Generic_type_0_requires_1_type_argument_s: diag(2314, ts.DiagnosticCategory.Error, "Generic_type_0_requires_1_type_argument_s_2314", "Generic type '{0}' requires {1} type argument(s)."), @@ -8500,7 +8500,7 @@ var ts; Parameter_0_cannot_reference_identifier_1_declared_after_it: diag(2373, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_identifier_1_declared_after_it_2373", "Parameter '{0}' cannot reference identifier '{1}' declared after it."), Duplicate_index_signature_for_type_0: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_index_signature_for_type_0_2374", "Duplicate index signature for type '{0}'."), Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2375, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefi_2375", "Type '{0}' is not assignable to type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), - A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", "A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers."), + A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2376, ts.DiagnosticCategory.Error, "A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_2376", "A 'super' call must be the first statement in the constructor to refer to 'super' or 'this' when a derived class contains initialized properties, parameter properties, or private identifiers."), Constructors_for_derived_classes_must_contain_a_super_call: diag(2377, ts.DiagnosticCategory.Error, "Constructors_for_derived_classes_must_contain_a_super_call_2377", "Constructors for derived classes must contain a 'super' call."), A_get_accessor_must_return_a_value: diag(2378, ts.DiagnosticCategory.Error, "A_get_accessor_must_return_a_value_2378", "A 'get' accessor must return a value."), Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties: diag(2379, ts.DiagnosticCategory.Error, "Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_tr_2379", "Argument of type '{0}' is not assignable to parameter of type '{1}' with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined' to the types of the target's properties."), @@ -8523,6 +8523,7 @@ var ts; constructor_cannot_be_used_as_a_parameter_property_name: diag(2398, ts.DiagnosticCategory.Error, "constructor_cannot_be_used_as_a_parameter_property_name_2398", "'constructor' cannot be used as a parameter property name."), Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: diag(2399, ts.DiagnosticCategory.Error, "Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference_2399", "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference."), Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: diag(2400, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference_2400", "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference."), + A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers: diag(2401, ts.DiagnosticCategory.Error, "A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_in_2401", "A 'super' call must be a root-level statement within a constructor of a derived class that contains initialized properties, parameter properties, or private identifiers."), Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference: diag(2402, ts.DiagnosticCategory.Error, "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402", "Expression resolves to '_super' that compiler uses to capture base class reference."), Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2: diag(2403, ts.DiagnosticCategory.Error, "Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_t_2403", "Subsequent variable declarations must have the same type. Variable '{0}' must be of type '{1}', but here has type '{2}'."), The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation: diag(2404, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation_2404", "The left-hand side of a 'for...in' statement cannot use a type annotation."), @@ -8881,12 +8882,10 @@ var ts; Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher: diag(2802, ts.DiagnosticCategory.Error, "Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es201_2802", "Type '{0}' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher."), Cannot_assign_to_private_method_0_Private_methods_are_not_writable: diag(2803, ts.DiagnosticCategory.Error, "Cannot_assign_to_private_method_0_Private_methods_are_not_writable_2803", "Cannot assign to private method '{0}'. Private methods are not writable."), Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name: diag(2804, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name_2804", "Duplicate identifier '{0}'. Static and instance elements cannot share the same private name."), - Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag: diag(2805, ts.DiagnosticCategory.Error, "Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_no_2805", "Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag."), Private_accessor_was_defined_without_a_getter: diag(2806, ts.DiagnosticCategory.Error, "Private_accessor_was_defined_without_a_getter_2806", "Private accessor was defined without a getter."), This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0: diag(2807, ts.DiagnosticCategory.Error, "This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_o_2807", "This syntax requires an imported helper named '{1}' with {2} parameters, which is not compatible with the one in '{0}'. Consider upgrading your version of '{0}'."), A_get_accessor_must_be_at_least_as_accessible_as_the_setter: diag(2808, ts.DiagnosticCategory.Error, "A_get_accessor_must_be_at_least_as_accessible_as_the_setter_2808", "A get accessor must be at least as accessible as the setter"), Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_destructuring_assignment_you_might_need_to_wrap_the_the_whole_assignment_in_parentheses: diag(2809, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_This_follows_a_block_of_statements_so_if_you_intended_to_write_a_d_2809", "Declaration or statement expected. This '=' follows a block of statements, so if you intended to write a destructuring assignment, you might need to wrap the the whole assignment in parentheses."), - Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false: diag(2810, ts.DiagnosticCategory.Error, "Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnex_2810", "Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'."), Initializer_for_property_0: diag(2811, ts.DiagnosticCategory.Error, "Initializer_for_property_0_2811", "Initializer for property '{0}'"), Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom: diag(2812, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom_2812", "Property '{0}' does not exist on type '{1}'. Try changing the 'lib' compiler option to include 'dom'."), Class_declaration_cannot_implement_overload_list_for_0: diag(2813, ts.DiagnosticCategory.Error, "Class_declaration_cannot_implement_overload_list_for_0_2813", "Class declaration cannot implement overload list for '{0}'."), @@ -8897,11 +8896,13 @@ var ts; Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers: diag(2818, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializer_2818", "Duplicate identifier '{0}'. Compiler reserves name '{1}' when emitting 'super' references in static initializers."), Namespace_name_cannot_be_0: diag(2819, ts.DiagnosticCategory.Error, "Namespace_name_cannot_be_0_2819", "Namespace name cannot be '{0}'."), Type_0_is_not_assignable_to_type_1_Did_you_mean_2: diag(2820, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Did_you_mean_2_2820", "Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?"), - Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext'."), + Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext: diag(2821, ts.DiagnosticCategory.Error, "Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext_2821", "Import assertions are only supported when the '--module' option is set to 'esnext' or 'nodenext'."), Import_assertions_cannot_be_used_with_type_only_imports_or_exports: diag(2822, ts.DiagnosticCategory.Error, "Import_assertions_cannot_be_used_with_type_only_imports_or_exports_2822", "Import assertions cannot be used with type-only imports or exports."), Cannot_find_namespace_0_Did_you_mean_1: diag(2833, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_Did_you_mean_1_2833", "Cannot find namespace '{0}'. Did you mean '{1}'?"), Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Consider_adding_an_extension_to_the_import_path: diag(2834, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2834", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Consider adding an extension to the import path."), Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_node12_or_nodenext_Did_you_mean_0: diag(2835, ts.DiagnosticCategory.Error, "Relative_import_paths_need_explicit_file_extensions_in_EcmaScript_imports_when_moduleResolution_is_n_2835", "Relative import paths need explicit file extensions in EcmaScript imports when '--moduleResolution' is 'node12' or 'nodenext'. Did you mean '{0}'?"), + Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls: diag(2836, ts.DiagnosticCategory.Error, "Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls_2836", "Import assertions are not allowed on statements that transpile to commonjs 'require' calls."), + Import_assertion_values_must_be_string_literal_expressions: diag(2837, ts.DiagnosticCategory.Error, "Import_assertion_values_must_be_string_literal_expressions_2837", "Import assertion values must be string literal expressions."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -9100,6 +9101,7 @@ var ts; DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"), STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"), FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"), + Errors_Files: diag(6041, ts.DiagnosticCategory.Message, "Errors_Files_6041", "Errors Files"), Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."), Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."), Unterminated_quoted_string_in_response_file_0: diag(6045, ts.DiagnosticCategory.Error, "Unterminated_quoted_string_in_response_file_0_6045", "Unterminated quoted string in response file '{0}'."), @@ -9293,6 +9295,9 @@ var ts; Output_Formatting: diag(6256, ts.DiagnosticCategory.Message, "Output_Formatting_6256", "Output Formatting"), Completeness: diag(6257, ts.DiagnosticCategory.Message, "Completeness_6257", "Completeness"), _0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file: diag(6258, ts.DiagnosticCategory.Error, "_0_should_be_set_inside_the_compilerOptions_object_of_the_config_json_file_6258", "'{0}' should be set inside the 'compilerOptions' object of the config json file"), + Found_1_error_in_1: diag(6259, ts.DiagnosticCategory.Message, "Found_1_error_in_1_6259", "Found 1 error in {1}"), + Found_0_errors_in_the_same_file_starting_at_Colon_1: diag(6260, ts.DiagnosticCategory.Message, "Found_0_errors_in_the_same_file_starting_at_Colon_1_6260", "Found {0} errors in the same file, starting at: {1}"), + Found_0_errors_in_1_files: diag(6261, ts.DiagnosticCategory.Message, "Found_0_errors_in_1_files_6261", "Found {0} errors in {1} files."), Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve: diag(6270, ts.DiagnosticCategory.Message, "Directory_0_has_no_containing_package_json_scope_Imports_will_not_resolve_6270", "Directory '{0}' has no containing package.json scope. Imports will not resolve."), Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1: diag(6271, ts.DiagnosticCategory.Message, "Import_specifier_0_does_not_exist_in_package_json_scope_at_path_1_6271", "Import specifier '{0}' does not exist in package.json scope at path '{1}'."), Invalid_import_specifier_0_has_no_possible_resolutions: diag(6272, ts.DiagnosticCategory.Message, "Invalid_import_specifier_0_has_no_possible_resolutions_6272", "Invalid import specifier '{0}' has no possible resolutions."), @@ -9637,9 +9642,8 @@ var ts; Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"), Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"), Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"), - Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""), + Import_0_from_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_1_90013", "Import '{0}' from \"{1}\""), Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"), - Add_0_to_existing_import_declaration_from_1: diag(90015, ts.DiagnosticCategory.Message, "Add_0_to_existing_import_declaration_from_1_90015", "Add '{0}' to existing import declaration from \"{1}\""), Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"), Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"), Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"), @@ -9656,8 +9660,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"), Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"), - Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""), - Add_default_import_0_to_existing_import_declaration_from_1: diag(90033, ts.DiagnosticCategory.Message, "Add_default_import_0_to_existing_import_declaration_from_1_90033", "Add default import '{0}' to existing import declaration from \"{1}\""), Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"), Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"), Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"), @@ -9667,6 +9669,10 @@ var ts; Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"), Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."), Includes_imports_of_types_referenced_by_0: diag(90054, ts.DiagnosticCategory.Message, "Includes_imports_of_types_referenced_by_0_90054", "Includes imports of types referenced by '{0}'"), + Remove_type_from_import_declaration_from_0: diag(90055, ts.DiagnosticCategory.Message, "Remove_type_from_import_declaration_from_0_90055", "Remove 'type' from import declaration from \"{0}\""), + Remove_type_from_import_of_0_from_1: diag(90056, ts.DiagnosticCategory.Message, "Remove_type_from_import_of_0_from_1_90056", "Remove 'type' from import of '{0}' from \"{1}\""), + Add_import_from_0: diag(90057, ts.DiagnosticCategory.Message, "Add_import_from_0_90057", "Add import from \"{0}\""), + Update_import_from_0: diag(90058, ts.DiagnosticCategory.Message, "Update_import_from_0_90058", "Update import from \"{0}\""), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -9830,6 +9836,10 @@ var ts; Add_missing_attributes: diag(95167, ts.DiagnosticCategory.Message, "Add_missing_attributes_95167", "Add missing attributes"), Add_all_missing_attributes: diag(95168, ts.DiagnosticCategory.Message, "Add_all_missing_attributes_95168", "Add all missing attributes"), Add_undefined_to_optional_property_type: diag(95169, ts.DiagnosticCategory.Message, "Add_undefined_to_optional_property_type_95169", "Add 'undefined' to optional property type"), + Convert_named_imports_to_default_import: diag(95170, ts.DiagnosticCategory.Message, "Convert_named_imports_to_default_import_95170", "Convert named imports to default import"), + Delete_unused_param_tag_0: diag(95171, ts.DiagnosticCategory.Message, "Delete_unused_param_tag_0_95171", "Delete unused '@param' tag '{0}'"), + Delete_all_unused_param_tags: diag(95172, ts.DiagnosticCategory.Message, "Delete_all_unused_param_tags_95172", "Delete all unused '@param' tags"), + Rename_param_tag_name_0_to_1: diag(95173, ts.DiagnosticCategory.Message, "Rename_param_tag_name_0_to_1_95173", "Rename '@param' tag name '{0}' to '{1}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -11928,6 +11938,7 @@ var ts; tokenValue = tokenValue.slice(0, -1); pos--; } + return getIdentifierToken(); } return token; } @@ -12173,6 +12184,8 @@ var ts; switch (ts.getEmitScriptTarget(options)) { case 99 /* ESNext */: return "lib.esnext.full.d.ts"; + case 9 /* ES2022 */: + return "lib.es2022.full.d.ts"; case 8 /* ES2021 */: return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: @@ -12999,12 +13012,17 @@ var ts; /** Gets the text of a jsdoc comment, flattening links to their text. */ function getTextOfJSDocComment(comment) { return typeof comment === "string" ? comment - : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { - // TODO: Other kinds here - return c.kind === 319 /* JSDocText */ ? c.text : "{@link ".concat(c.name ? ts.entityNameToString(c.name) + " " : "").concat(c.text, "}"); - }).join(""); + : comment === null || comment === void 0 ? void 0 : comment.map(function (c) { return c.kind === 319 /* JSDocText */ ? c.text : formatJSDocLink(c); }).join(""); } ts.getTextOfJSDocComment = getTextOfJSDocComment; + function formatJSDocLink(link) { + var kind = link.kind === 322 /* JSDocLink */ ? "link" + : link.kind === 323 /* JSDocLinkCode */ ? "linkcode" + : "linkplain"; + var name = link.name ? ts.entityNameToString(link.name) : ""; + var space = link.name && link.text.startsWith("://") ? "" : " "; + return "{@".concat(kind, " ").concat(name).concat(space).concat(link.text, "}"); + } /** * Gets the effective type parameters. If the node was parsed in a * JavaScript file, gets the type parameters from the `@template` tag from JSDoc. @@ -14083,21 +14101,10 @@ var ts; return undefined; } ts.getDeclarationOfKind = getDeclarationOfKind; - /** - * Create a new escaped identifier map. - * @deprecated Use `new Map<__String, T>()` instead. - */ - function createUnderscoreEscapedMap() { - return new ts.Map(); + function getDeclarationsOfKind(symbol, kind) { + return ts.filter(symbol.declarations || ts.emptyArray, function (d) { return d.kind === kind; }); } - ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; - /** - * @deprecated Use `!!map?.size` instead - */ - function hasEntries(map) { - return !!map && !!map.size; - } - ts.hasEntries = hasEntries; + ts.getDeclarationsOfKind = getDeclarationsOfKind; function createSymbolTable(symbols) { var result = new ts.Map(); if (symbols) { @@ -14269,10 +14276,13 @@ var ts; function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } - function packageIdToString(_a) { - var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; - var fullName = subModuleName ? "".concat(name, "/").concat(subModuleName) : name; - return "".concat(fullName, "@").concat(version); + function packageIdToPackageName(_a) { + var name = _a.name, subModuleName = _a.subModuleName; + return subModuleName ? "".concat(name, "/").concat(subModuleName) : name; + } + ts.packageIdToPackageName = packageIdToPackageName; + function packageIdToString(packageId) { + return "".concat(packageIdToPackageName(packageId), "@").concat(packageId.version); } ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { @@ -14330,6 +14340,10 @@ var ts; return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module)); } ts.getSourceFileOfModule = getSourceFileOfModule; + function isPlainJsFile(file, checkJs) { + return !!file && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */) && !file.checkJsDirective && checkJs === undefined; + } + ts.isPlainJsFile = isPlainJsFile; function isStatementWithLocals(node) { switch (node.kind) { case 234 /* Block */: @@ -14639,6 +14653,7 @@ var ts; AsyncIterableIterator: ts.emptyArray, AsyncGenerator: ts.emptyArray, AsyncGeneratorFunction: ts.emptyArray, + NumberFormat: ["formatToParts"] }, es2019: { Array: ["flat", "flatMap"], @@ -14660,8 +14675,22 @@ var ts; PromiseConstructor: ["any"], String: ["replaceAll"] }, - esnext: { - NumberFormat: ["formatToParts"] + es2022: { + Array: ["at"], + String: ["at"], + Int8Array: ["at"], + Uint8Array: ["at"], + Uint8ClampedArray: ["at"], + Int16Array: ["at"], + Uint16Array: ["at"], + Int32Array: ["at"], + Uint32Array: ["at"], + Float32Array: ["at"], + Float64Array: ["at"], + BigInt64Array: ["at"], + BigUint64Array: ["at"], + ObjectConstructor: ["hasOwn"], + Error: ["cause"] } }; } @@ -15090,6 +15119,15 @@ var ts; }; } ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain; + function createDiagnosticMessageChainFromDiagnostic(diagnostic) { + return typeof diagnostic.messageText === "string" ? { + code: diagnostic.code, + category: diagnostic.category, + messageText: diagnostic.messageText, + next: diagnostic.next, + } : diagnostic.messageText; + } + ts.createDiagnosticMessageChainFromDiagnostic = createDiagnosticMessageChainFromDiagnostic; function createDiagnosticForRange(sourceFile, range, message) { return { file: sourceFile, @@ -15258,7 +15296,8 @@ var ts; node.kind === 212 /* FunctionExpression */ || node.kind === 213 /* ArrowFunction */ || node.kind === 211 /* ParenthesizedExpression */ || - node.kind === 253 /* VariableDeclaration */) ? + node.kind === 253 /* VariableDeclaration */ || + node.kind === 274 /* ExportSpecifier */) ? ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) : ts.getLeadingCommentRanges(text, node.pos); // True if the comment starts with '/**' but not if it is '/**/' @@ -15675,6 +15714,34 @@ var ts; } } ts.getThisContainer = getThisContainer; + /** + * @returns Whether the node creates a new 'this' scope for its children. + */ + function isThisContainerOrFunctionBlock(node) { + switch (node.kind) { + // Arrow functions use the same scope, but may do so in a "delayed" manner + // For example, `const getThis = () => this` may be before a super() call in a derived constructor + case 213 /* ArrowFunction */: + case 255 /* FunctionDeclaration */: + case 212 /* FunctionExpression */: + case 166 /* PropertyDeclaration */: + return true; + case 234 /* Block */: + switch (node.parent.kind) { + case 170 /* Constructor */: + case 168 /* MethodDeclaration */: + case 171 /* GetAccessor */: + case 172 /* SetAccessor */: + // Object properties can have computed names; only method-like bodies start a new scope + return true; + default: + return false; + } + default: + return false; + } + } + ts.isThisContainerOrFunctionBlock = isThisContainerOrFunctionBlock; function isInTopLevelContext(node) { // The name of a class or function declaration is a BindingIdentifier in its surrounding scope. if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) { @@ -16033,7 +16100,7 @@ var ts; } ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression; function getExternalModuleRequireArgument(node) { - return isRequireVariableDeclaration(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; + return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && getLeftmostAccessExpression(node.initializer).arguments[0]; } ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument; function isInternalModuleImportEqualsDeclaration(node) { @@ -16091,17 +16158,29 @@ var ts; * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). * This function does not test if the node is in a JavaScript file or not. */ - function isRequireVariableDeclaration(node) { + function isVariableDeclarationInitializedToRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ false); + } + ts.isVariableDeclarationInitializedToRequire = isVariableDeclarationInitializedToRequire; + /** + * Like {@link isVariableDeclarationInitializedToRequire} but allows things like `require("...").foo.bar` or `require("...")["baz"]`. + */ + function isVariableDeclarationInitializedToBareOrAccessedRequire(node) { + return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ true); + } + ts.isVariableDeclarationInitializedToBareOrAccessedRequire = isVariableDeclarationInitializedToBareOrAccessedRequire; + function isVariableDeclarationInitializedWithRequireHelper(node, allowAccessedRequire) { if (node.kind === 202 /* BindingElement */) { node = node.parent.parent; } - return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true); + return ts.isVariableDeclaration(node) && + !!node.initializer && + isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); } - ts.isRequireVariableDeclaration = isRequireVariableDeclaration; function isRequireVariableStatement(node) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 - && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl); }); + && ts.every(node.declarationList.declarations, function (decl) { return isVariableDeclarationInitializedToRequire(decl); }); } ts.isRequireVariableStatement = isRequireVariableStatement; function isSingleOrDoubleQuote(charCode) { @@ -19588,7 +19667,7 @@ var ts; getSourceMapSourceConstructor: function () { return SourceMapSource; }, }; function setObjectAllocator(alloc) { - ts.objectAllocator = alloc; + Object.assign(ts.objectAllocator, alloc); } ts.setObjectAllocator = setObjectAllocator; function formatStringFromArgs(text, args, baseIndex) { @@ -19596,13 +19675,22 @@ var ts; return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); }); } ts.formatStringFromArgs = formatStringFromArgs; + var localizedDiagnosticMessages; /* @internal */ function setLocalizedDiagnosticMessages(messages) { - ts.localizedDiagnosticMessages = messages; + localizedDiagnosticMessages = messages; } ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages; + /* @internal */ + // If the localized messages json is unset, and if given function use it to set the json + function maybeSetLocalizedDiagnosticMessages(getMessages) { + if (!localizedDiagnosticMessages && getMessages) { + localizedDiagnosticMessages = getMessages(); + } + } + ts.maybeSetLocalizedDiagnosticMessages = maybeSetLocalizedDiagnosticMessages; function getLocaleSpecificMessage(message) { - return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message; + return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } ts.getLocaleSpecificMessage = getLocaleSpecificMessage; function createDetachedDiagnostic(fileName, start, length, message) { @@ -19921,7 +20009,7 @@ var ts; } ts.getAllowJSCompilerOption = getAllowJSCompilerOption; function getUseDefineForClassFields(compilerOptions) { - return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ : compilerOptions.useDefineForClassFields; + return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } ts.getUseDefineForClassFields = getUseDefineForClassFields; function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) { @@ -19995,16 +20083,6 @@ var ts; (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real); } }, - setSymlinkedDirectoryFromSymlinkedFile: function (symlink, real) { - this.setSymlinkedFile(ts.toPath(symlink, cwd, getCanonicalFileName), real); - var _a = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _a[0], commonOriginal = _a[1]; - if (commonResolved && commonOriginal) { - this.setSymlinkedDirectory(commonOriginal, { - real: commonResolved, - realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName), - }); - } - }, setSymlinksFromResolutions: function (files, typeReferenceDirectives) { var _this = this; var _a; @@ -20972,9 +21050,97 @@ var ts; } ts.isFunctionExpressionOrArrowFunction = isFunctionExpressionOrArrowFunction; function escapeSnippetText(text) { - return text.replace(/\$/gm, "\\$"); + return text.replace(/\$/gm, function () { return "\\$"; }); } ts.escapeSnippetText = escapeSnippetText; + function isNumericLiteralName(name) { + // The intent of numeric names is that + // - they are names with text in a numeric form, and that + // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', + // acquired by applying the abstract 'ToNumber' operation on the name's text. + // + // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. + // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. + // + // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' + // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. + // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names + // because their 'ToString' representation is not equal to their original text. + // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. + // + // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. + // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. + // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. + // + // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. + // This is desired behavior, because when indexing with them as numeric entities, you are indexing + // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. + return (+name).toString() === name; + } + ts.isNumericLiteralName = isNumericLiteralName; + function createPropertyNameNodeForIdentifierOrLiteral(name, target, singleQuote, stringNamed) { + return ts.isIdentifierText(name, target) ? ts.factory.createIdentifier(name) : + !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) : + ts.factory.createStringLiteral(name, !!singleQuote); + } + ts.createPropertyNameNodeForIdentifierOrLiteral = createPropertyNameNodeForIdentifierOrLiteral; + function isThisTypeParameter(type) { + return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); + } + ts.isThisTypeParameter = isThisTypeParameter; + function getNodeModulePathParts(fullPath) { + // If fullPath can't be valid module file within node_modules, returns undefined. + // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js + // Returns indices: ^ ^ ^ ^ + var topLevelNodeModulesIndex = 0; + var topLevelPackageNameIndex = 0; + var packageRootIndex = 0; + var fileNameIndex = 0; + var States; + (function (States) { + States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; + States[States["NodeModules"] = 1] = "NodeModules"; + States[States["Scope"] = 2] = "Scope"; + States[States["PackageContent"] = 3] = "PackageContent"; + })(States || (States = {})); + var partStart = 0; + var partEnd = 0; + var state = 0 /* BeforeNodeModules */; + while (partEnd >= 0) { + partStart = partEnd; + partEnd = fullPath.indexOf("/", partStart + 1); + switch (state) { + case 0 /* BeforeNodeModules */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + topLevelNodeModulesIndex = partStart; + topLevelPackageNameIndex = partEnd; + state = 1 /* NodeModules */; + } + break; + case 1 /* NodeModules */: + case 2 /* Scope */: + if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { + state = 2 /* Scope */; + } + else { + packageRootIndex = partEnd; + state = 3 /* PackageContent */; + } + break; + case 3 /* PackageContent */: + if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { + state = 1 /* NodeModules */; + } + else { + state = 3 /* PackageContent */; + } + break; + } + } + fileNameIndex = partStart; + return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; + } + ts.getNodeModulePathParts = getNodeModulePathParts; })(ts || (ts = {})); /* @internal */ var ts; @@ -22199,7 +22365,7 @@ var ts; var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value); node.numericLiteralFlags = numericLiteralFlags; if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -22218,7 +22384,7 @@ var ts; var node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; if (hasExtendedUnicodeEscape) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -22346,8 +22512,8 @@ var ts; case 131 /* AsyncKeyword */: // 'async' modifier is ES2017 (async functions) or ES2018 (async generators) transformFlags = - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; break; case 123 /* PublicKeyword */: case 121 /* PrivateKeyword */: @@ -22371,10 +22537,10 @@ var ts; transformFlags = 1 /* ContainsTypeScript */; break; case 106 /* SuperKeyword */: - transformFlags = 512 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */; + transformFlags = 1024 /* ContainsES2015 */ | 33554432 /* ContainsLexicalSuper */; break; case 124 /* StaticKeyword */: - transformFlags = 512 /* ContainsES2015 */; + transformFlags = 1024 /* ContainsES2015 */; break; case 108 /* ThisKeyword */: // 'this' indicates a lexical 'this' @@ -22443,7 +22609,7 @@ var ts; result.push(createModifier(144 /* ReadonlyKeyword */)); if (flags & 256 /* Async */) result.push(createModifier(131 /* AsyncKeyword */)); - return result; + return result.length ? result : undefined; } // // Names @@ -22471,7 +22637,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 65536 /* ContainsComputedPropertyName */; return node; } @@ -22519,7 +22685,7 @@ var ts; if (ts.modifiersToFlags(node.modifiers) & 16476 /* ParameterPropertyModifier */) node.transformFlags |= 4096 /* ContainsTypeScriptClassSyntax */; if (initializer || dotDotDotToken) - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; } return node; } @@ -22628,20 +22794,20 @@ var ts; node.transformFlags |= propagateChildFlags(node.asteriskToken) | propagateChildFlags(node.questionToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (questionToken) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } return node; } @@ -22682,7 +22848,7 @@ var ts; /*name*/ undefined, /*typeParameters*/ undefined, parameters, /*type*/ undefined, body); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -23176,11 +23342,11 @@ var ts; node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 262144 /* ContainsBindingPattern */; if (node.transformFlags & 16384 /* ContainsRestOrSpread */) { node.transformFlags |= - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 32768 /* ContainsObjectRestOrSpread */; } return node; @@ -23197,7 +23363,7 @@ var ts; node.elements = createNodeArray(elements); node.transformFlags |= propagateChildrenFlags(node.elements) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 262144 /* ContainsBindingPattern */; return node; } @@ -23216,7 +23382,7 @@ var ts; node.dotDotDotToken = dotDotDotToken; node.transformFlags |= propagateChildFlags(node.dotDotDotToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (node.propertyName) { node.transformFlags |= ts.isIdentifier(node.propertyName) ? propagateIdentifierNameFlags(node.propertyName) : @@ -23290,8 +23456,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; } return node; } @@ -23313,7 +23479,7 @@ var ts; node.questionDotToken = questionDotToken; node.name = asName(name); node.transformFlags |= - 16 /* ContainsES2020 */ | + 32 /* ContainsES2020 */ | propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | (ts.isIdentifier(node.name) ? @@ -23344,8 +23510,8 @@ var ts; // super method calls require a lexical 'this' // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators node.transformFlags |= - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */; + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */; } return node; } @@ -23370,7 +23536,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildFlags(node.questionDotToken) | propagateChildFlags(node.argumentExpression) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; return node; } // @api @@ -23429,7 +23595,7 @@ var ts; propagateChildFlags(node.questionDotToken) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -23458,7 +23624,7 @@ var ts; propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | propagateChildrenFlags(node.arguments) | - 16 /* ContainsES2020 */; + 32 /* ContainsES2020 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -23482,12 +23648,12 @@ var ts; propagateChildFlags(node.tag) | propagateChildrenFlags(node.typeArguments) | propagateChildFlags(node.template) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (node.typeArguments) { node.transformFlags |= 1 /* ContainsTypeScript */; } if (ts.hasInvalidEscape(node.template)) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } return node; } @@ -23541,14 +23707,14 @@ var ts; } if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } return node; } @@ -23572,9 +23738,9 @@ var ts; node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */); node.transformFlags |= propagateChildFlags(node.equalsGreaterThanToken) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { - node.transformFlags |= 128 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */; + node.transformFlags |= 256 /* ContainsES2017 */ | 8192 /* ContainsLexicalThis */; } return node; } @@ -23634,8 +23800,8 @@ var ts; node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 128 /* ContainsES2017 */ | - 64 /* ContainsES2018 */ | + 256 /* ContainsES2017 */ | + 128 /* ContainsES2018 */ | 1048576 /* ContainsAwait */; return node; } @@ -23701,35 +23867,35 @@ var ts; propagateChildFlags(node.operatorToken) | propagateChildFlags(node.right); if (operatorKind === 60 /* QuestionQuestionToken */) { - node.transformFlags |= 16 /* ContainsES2020 */; + node.transformFlags |= 32 /* ContainsES2020 */; } else if (operatorKind === 63 /* EqualsToken */) { if (ts.isObjectLiteralExpression(node.left)) { node.transformFlags |= - 512 /* ContainsES2015 */ | - 64 /* ContainsES2018 */ | - 2048 /* ContainsDestructuringAssignment */ | + 1024 /* ContainsES2015 */ | + 128 /* ContainsES2018 */ | + 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } else if (ts.isArrayLiteralExpression(node.left)) { node.transformFlags |= - 512 /* ContainsES2015 */ | - 2048 /* ContainsDestructuringAssignment */ | + 1024 /* ContainsES2015 */ | + 4096 /* ContainsDestructuringAssignment */ | propagateAssignmentPatternFlags(node.left); } } else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 67 /* AsteriskAsteriskEqualsToken */) { - node.transformFlags |= 256 /* ContainsES2016 */; + node.transformFlags |= 512 /* ContainsES2016 */; } else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) { - node.transformFlags |= 8 /* ContainsES2021 */; + node.transformFlags |= 16 /* ContainsES2021 */; } return node; } function propagateAssignmentPatternFlags(node) { if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) return 32768 /* ContainsObjectRestOrSpread */; - if (node.transformFlags & 64 /* ContainsES2018 */) { + if (node.transformFlags & 128 /* ContainsES2018 */) { // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c' // will not be correctly interpreted by the ES2018 transformer for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) { @@ -23739,7 +23905,7 @@ var ts; if (target.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { return 32768 /* ContainsObjectRestOrSpread */; } - if (target.transformFlags & 64 /* ContainsES2018 */) { + if (target.transformFlags & 128 /* ContainsES2018 */) { var flags_1 = propagateAssignmentPatternFlags(target); if (flags_1) return flags_1; @@ -23791,7 +23957,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.head) | propagateChildrenFlags(node.templateSpans) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -23830,9 +23996,9 @@ var ts; node.text = text; node.rawText = rawText; node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */; - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; if (node.templateFlags) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } return node; } @@ -23861,8 +24027,8 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.asteriskToken) | - 512 /* ContainsES2015 */ | - 64 /* ContainsES2018 */ | + 1024 /* ContainsES2015 */ | + 128 /* ContainsES2018 */ | 524288 /* ContainsYield */; return node; } @@ -23879,7 +24045,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 16384 /* ContainsRestOrSpread */; return node; } @@ -23892,7 +24058,7 @@ var ts; // @api function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) { var node = createBaseClassLikeDeclaration(225 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @api @@ -23918,7 +24084,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildrenFlags(node.typeArguments) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -23989,7 +24155,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.name); switch (keywordToken) { case 103 /* NewKeyword */: - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; break; case 100 /* ImportKeyword */: node.transformFlags |= 4 /* ContainsESNext */; @@ -24016,7 +24182,7 @@ var ts; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.literal) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } // @api @@ -24029,7 +24195,7 @@ var ts; // @api function createSemicolonClassElement() { var node = createBaseNode(233 /* SemicolonClassElement */); - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; return node; } // @@ -24193,9 +24359,9 @@ var ts; propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; if (awaitModifier) - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; return node; } // @api @@ -24244,7 +24410,7 @@ var ts; // return in an ES2018 async generator must be awaited node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */; return node; } @@ -24374,7 +24540,7 @@ var ts; 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (flags & 3 /* BlockScoped */) { node.transformFlags |= - 512 /* ContainsES2015 */ | + 1024 /* ContainsES2015 */ | 131072 /* ContainsBlockScopedBinding */; } return node; @@ -24398,14 +24564,14 @@ var ts; 2097152 /* ContainsHoistedDeclarationOrCompletion */; if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) { if (node.asteriskToken) { - node.transformFlags |= 64 /* ContainsES2018 */; + node.transformFlags |= 128 /* ContainsES2018 */; } else { - node.transformFlags |= 128 /* ContainsES2017 */; + node.transformFlags |= 256 /* ContainsES2017 */; } } else if (node.asteriskToken) { - node.transformFlags |= 1024 /* ContainsGenerator */; + node.transformFlags |= 2048 /* ContainsGenerator */; } } return node; @@ -24430,7 +24596,7 @@ var ts; node.transformFlags = 1 /* ContainsTypeScript */; } else { - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; if (node.transformFlags & 4096 /* ContainsTypeScriptClassSyntax */) { node.transformFlags |= 1 /* ContainsTypeScript */; } @@ -24639,7 +24805,7 @@ var ts; // @api function createAssertClause(elements, multiLine) { var node = createBaseNode(292 /* AssertClause */); - node.elements = elements; + node.elements = createNodeArray(elements); node.multiLine = multiLine; node.transformFlags |= 4 /* ContainsESNext */; return node; @@ -25470,7 +25636,7 @@ var ts; node.transformFlags |= propagateChildrenFlags(node.types); switch (token) { case 94 /* ExtendsKeyword */: - node.transformFlags |= 512 /* ContainsES2015 */; + node.transformFlags |= 1024 /* ContainsES2015 */; break; case 117 /* ImplementsKeyword */: node.transformFlags |= 1 /* ContainsTypeScript */; @@ -25501,7 +25667,7 @@ var ts; propagateChildFlags(node.variableDeclaration) | propagateChildFlags(node.block); if (!variableDeclaration) - node.transformFlags |= 32 /* ContainsES2019 */; + node.transformFlags |= 64 /* ContainsES2019 */; return node; } // @api @@ -25552,7 +25718,7 @@ var ts; node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer); node.transformFlags |= propagateChildFlags(node.objectAssignmentInitializer) | - 512 /* ContainsES2015 */; + 1024 /* ContainsES2015 */; return node; } function finishUpdateShorthandPropertyAssignment(updated, original) { @@ -25582,7 +25748,7 @@ var ts; node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.transformFlags |= propagateChildFlags(node.expression) | - 64 /* ContainsES2018 */ | + 128 /* ContainsES2018 */ | 32768 /* ContainsObjectRestOrSpread */; return node; } @@ -26236,7 +26402,7 @@ var ts; * @param visitor Optional callback used to visit any custom prologue directives. */ function copyPrologue(source, target, ensureUseStrict, visitor) { - var offset = copyStandardPrologue(source, target, ensureUseStrict); + var offset = copyStandardPrologue(source, target, 0, ensureUseStrict); return copyCustomPrologue(source, target, offset, visitor); } function isUseStrictPrologue(node) { @@ -26249,12 +26415,14 @@ var ts; * Copies only the standard (string-expression) prologue-directives into the target statement-array. * @param source origin statements array * @param target result statements array + * @param statementOffset The offset at which to begin the copy. * @param ensureUseStrict boolean determining whether the function need to add prologue-directives + * @returns Count of how many directive statements were copied. */ - function copyStandardPrologue(source, target, ensureUseStrict) { + function copyStandardPrologue(source, target, statementOffset, ensureUseStrict) { + if (statementOffset === void 0) { statementOffset = 0; } ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); var foundUseStrict = false; - var statementOffset = 0; var numStatements = source.length; while (statementOffset < numStatements) { var statement = source[statementOffset]; @@ -26400,32 +26568,36 @@ var ts; } function updateModifiers(node, modifiers) { var _a; + var modifierArray; if (typeof modifiers === "number") { - modifiers = createModifiersFromModifierFlags(modifiers); - } - return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : - ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) : - ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : - ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : - ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : - ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) : - ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) : - ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) : - ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) : - ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : - ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) : - ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : - ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) : - ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) : - ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) : - ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) : - ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) : - ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier, node.assertClause) : - ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) : - ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : + modifierArray = createModifiersFromModifierFlags(modifiers); + } + else { + modifierArray = modifiers; + } + return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) : + ts.isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) : + ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) : + ts.isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) : + ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) : + ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) : + ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) : + ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) : + ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) : + ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) : + ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) : + ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) : + ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) : + ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) : + ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) : + ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) : + ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) : + ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) : + ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) : + ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) : ts.Debug.assertNever(node); } function asNodeArray(array) { @@ -26676,7 +26848,7 @@ var ts; sourceMapText = mapTextOrStripInternal; } var node = oldFileOfCurrentEmit ? - parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) : + parseOldFileOfCurrentEmit(ts.Debug.checkDefined(bundleFileInfo)) : parseUnparsedSourceFile(bundleFileInfo, stripInternal, length); node.fileName = fileName; node.sourceMapPath = sourceMapPath; @@ -26823,13 +26995,13 @@ var ts; }; node.javascriptPath = declarationTextOrJavascriptPath; node.javascriptMapPath = javascriptMapPath; - node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath); + node.declarationPath = ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath); node.declarationMapPath = declarationMapPath; node.buildInfoPath = declarationMapTextOrBuildInfoPath; Object.defineProperties(node, { javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } }, javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } }, - declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } }, + declarationText: { get: function () { return definedTextGetter_1(ts.Debug.checkDefined(javascriptMapTextOrDeclarationPath)); } }, declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } }, buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } } }); @@ -27673,7 +27845,7 @@ var ts; importName: "__createBinding", scoped: false, priority: 1, - text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));" + text: "\n var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n }));" }; ts.setModuleDefaultHelper = { name: "typescript:commonjscreatevalue", @@ -33732,7 +33904,7 @@ var ts; return true; } } - else if (third === 27 /* CommaToken */) { + else if (third === 27 /* CommaToken */ || third === 63 /* EqualsToken */) { return true; } return false; @@ -33825,9 +33997,14 @@ var ts; // - "(x,y)" is a comma expression parsed as a signature with two parameters. // - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation. // - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type. + // - "a ? (b): (function() {})" as well, but inside of a parenthesized type with an arbitrary amount of nesting. // // So we need just a bit of lookahead to ensure that it can only be a signature. - var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type); + var unwrappedType = type; + while ((unwrappedType === null || unwrappedType === void 0 ? void 0 : unwrappedType.kind) === 190 /* ParenthesizedType */) { + unwrappedType = unwrappedType.type; // Skip parens if need be + } + var hasJSDocFunctionType = unwrappedType && ts.isJSDocFunctionType(unwrappedType); if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) { // Returning undefined here will cause our caller to rewind to where we started from. return undefined; @@ -35175,7 +35352,7 @@ var ts; // one out no matter what. var finallyBlock; if (!catchClause || token() === 96 /* FinallyKeyword */) { - parseExpected(96 /* FinallyKeyword */); + parseExpected(96 /* FinallyKeyword */, ts.Diagnostics.catch_or_finally_expected); finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); } return withJSDoc(finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos), hasJSDoc); @@ -36219,7 +36396,7 @@ var ts; var pos = getNodePos(); var name = ts.tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(10 /* StringLiteral */); parseExpected(58 /* ColonToken */); - var value = parseLiteralLikeNode(10 /* StringLiteral */); + var value = parseAssignmentExpressionOrHigher(); return finishNode(factory.createAssertEntry(name, value), pos); } function parseAssertClause() { @@ -36324,7 +36501,8 @@ var ts; return finishNode(node, pos); } function parseExportSpecifier() { - return parseImportOrExportSpecifier(274 /* ExportSpecifier */); + var hasJSDoc = hasPrecedingJSDocComment(); + return withJSDoc(parseImportOrExportSpecifier(274 /* ExportSpecifier */), hasJSDoc); } function parseImportSpecifier() { return parseImportOrExportSpecifier(269 /* ImportSpecifier */); @@ -38226,7 +38404,11 @@ var ts; var ts; (function (ts) { /* @internal */ - ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean", defaultValueDescription: "false" }; + ts.compileOnSaveCommandLineOption = { + name: "compileOnSave", + type: "boolean", + defaultValueDescription: false, + }; var jsxOptionMap = new ts.Map(ts.getEntries({ "preserve": 1 /* Preserve */, "react-native": 3 /* ReactNative */, @@ -38255,6 +38437,7 @@ var ts; ["es2019", "lib.es2019.d.ts"], ["es2020", "lib.es2020.d.ts"], ["es2021", "lib.es2021.d.ts"], + ["es2022", "lib.es2022.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -38299,17 +38482,18 @@ var ts; ["es2021.string", "lib.es2021.string.d.ts"], ["es2021.weakref", "lib.es2021.weakref.d.ts"], ["es2021.intl", "lib.es2021.intl.d.ts"], - ["esnext.array", "lib.es2019.array.d.ts"], + ["es2022.array", "lib.es2022.array.d.ts"], + ["es2022.error", "lib.es2022.error.d.ts"], + ["es2022.object", "lib.es2022.object.d.ts"], + ["es2022.string", "lib.es2022.string.d.ts"], + ["esnext.array", "lib.esnext.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], + ["esnext.string", "lib.es2022.string.d.ts"], ["esnext.promise", "lib.es2021.promise.d.ts"], - ["esnext.weakref", "lib.es2021.weakref.d.ts"], - ["esnext.array", "lib.esnext.array.d.ts"], - ["esnext.error", "lib.esnext.error.d.ts"], - ["esnext.object", "lib.esnext.object.d.ts"] + ["esnext.weakref", "lib.es2021.weakref.d.ts"] ]; /** * An array of supported "lib" reference file names used to determine the order for inclusion @@ -38339,6 +38523,7 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_how_the_TypeScript_watch_mode_works, + defaultValueDescription: ts.WatchFileKind.UseFsEvents, }, { name: "watchDirectory", @@ -38350,6 +38535,7 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality, + defaultValueDescription: ts.WatchDirectoryKind.UseFsEvents, }, { name: "fallbackPolling", @@ -38361,13 +38547,14 @@ var ts; })), category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers, + defaultValueDescription: ts.PollingWatchKind.PriorityInterval, }, { name: "synchronousWatchDirectory", type: "boolean", category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "excludeDirectories", @@ -38403,13 +38590,13 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_this_message, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "help", shortName: "?", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "watch", @@ -38419,7 +38606,7 @@ var ts; isCommandLineOnly: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Watch_input_files, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "preserveWatchOutput", @@ -38427,28 +38614,28 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_wiping_the_console_in_watch_mode, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_all_of_the_files_read_during_the_compilation, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "explainFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listEmittedFiles", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Print_the_names_of_emitted_files_after_a_compilation, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "pretty", @@ -38456,28 +38643,28 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read, - defaultValueDescription: "true" + defaultValueDescription: true, }, { name: "traceResolution", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Log_paths_used_during_the_moduleResolution_process, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "diagnostics", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Output_compiler_performance_information_after_building, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "extendedDiagnostics", type: "boolean", category: ts.Diagnostics.Compiler_Diagnostics, description: ts.Diagnostics.Output_more_detailed_compiler_performance_information_after_building, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "generateCpuProfile", @@ -38513,7 +38700,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Watch_and_Build_Modes, description: ts.Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "locale", @@ -38539,6 +38726,7 @@ var ts; es2019: 6 /* ES2019 */, es2020: 7 /* ES2020 */, es2021: 8 /* ES2021 */, + es2022: 9 /* ES2022 */, esnext: 99 /* ESNext */, })), affectsSourceFile: true, @@ -38548,7 +38736,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations, - defaultValueDescription: "ES3" + defaultValueDescription: 0 /* ES3 */, }; var commandOptionsWithoutBuild = [ // CommandLine only options @@ -38558,7 +38746,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_all_compiler_options, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "version", @@ -38567,7 +38755,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Print_the_compiler_s_version, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "init", @@ -38575,7 +38763,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "project", @@ -38594,7 +38782,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "showConfig", @@ -38603,7 +38791,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "listFilesOnly", @@ -38613,7 +38801,7 @@ var ts; affectsEmit: true, isCommandLineOnly: true, description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing, - defaultValueDescription: "false", + defaultValueDescription: false, }, // Basic ts.targetOptionDeclaration, @@ -38640,13 +38828,15 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Specify_what_module_code_is_generated, + defaultValueDescription: undefined, }, { name: "lib", type: "list", element: { name: "lib", - type: ts.libMap + type: ts.libMap, + defaultValueDescription: undefined, }, affectsProgramStructure: true, showInSimplifiedHelpView: true, @@ -38661,7 +38851,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "checkJs", @@ -38669,7 +38859,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "jsx", @@ -38681,7 +38871,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Specify_what_JSX_code_is_generated, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "declaration", @@ -38701,7 +38891,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Create_sourcemaps_for_d_ts_files }, { @@ -38712,7 +38902,7 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "sourceMap", @@ -38720,7 +38910,7 @@ var ts; affectsEmit: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Create_source_map_files_for_emitted_JavaScript_files, }, { @@ -38761,7 +38951,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, transpileOptionValue: undefined, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references, }, { @@ -38781,7 +38971,7 @@ var ts; affectsEmit: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Emit, - defaultValueDescription: "false", + defaultValueDescription: false, description: ts.Diagnostics.Disable_emitting_comments, }, { @@ -38791,7 +38981,7 @@ var ts; category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_files_from_a_compilation, transpileOptionValue: undefined, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "importHelpers", @@ -38799,7 +38989,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "importsNotUsedAsValues", @@ -38811,7 +39001,8 @@ var ts; affectsEmit: true, affectsSemanticDiagnostics: true, category: ts.Diagnostics.Emit, - description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types + description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types, + defaultValueDescription: 0 /* Remove */, }, { name: "downlevelIteration", @@ -38819,7 +39010,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "isolatedModules", @@ -38827,7 +39018,7 @@ var ts; category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports, transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Strict Type Checks { @@ -38838,7 +39029,7 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_all_strict_type_checking_options, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noImplicitAny", @@ -38899,7 +39090,7 @@ var ts; strictFlag: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "alwaysStrict", @@ -38917,7 +39108,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_when_a_local_variables_aren_t_read, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noUnusedParameters", @@ -38925,7 +39116,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "exactOptionalPropertyTypes", @@ -38933,7 +39124,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitReturns", @@ -38941,7 +39132,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noFallthroughCasesInSwitch", @@ -38950,7 +39141,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noUncheckedIndexedAccess", @@ -38958,7 +39149,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Include_undefined_in_index_signature_results, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitOverride", @@ -38966,7 +39157,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noPropertyAccessFromIndexSignature", @@ -38974,7 +39165,7 @@ var ts; showInSimplifiedHelpView: false, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Module Resolution { @@ -39068,14 +39259,14 @@ var ts; showInSimplifiedHelpView: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "preserveSymlinks", type: "boolean", category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "allowUmdGlobalAccess", @@ -39083,7 +39274,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Source Maps { @@ -39108,7 +39299,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "inlineSources", @@ -39116,7 +39307,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript, - defaultValueDescription: "false" + defaultValueDescription: false, }, // Experimental { @@ -39125,7 +39316,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "emitDecoratorMetadata", @@ -39134,7 +39325,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Language_and_Environment, description: ts.Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files, - defaultValueDescription: "false", + defaultValueDescription: false, }, // Advanced { @@ -39166,7 +39357,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.Modules, description: ts.Diagnostics.Enable_importing_json_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "out", @@ -39192,7 +39383,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "charset", @@ -39207,7 +39398,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "newLine", @@ -39227,7 +39418,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Output_Formatting, description: ts.Diagnostics.Disable_truncating_types_in_error_messages, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noLib", @@ -39238,7 +39429,7 @@ var ts; // We are not returning a sourceFile for lib file when asked by the program, // so pass --noLib to avoid reporting a file not found error. transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noResolve", @@ -39249,7 +39440,7 @@ var ts; // We are not doing a full typecheck, we are not resolving the whole context, // so pass --noResolve to avoid reporting missing file errors. transpileOptionValue: true, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "stripInternal", @@ -39257,7 +39448,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableSizeLimit", @@ -39265,7 +39456,7 @@ var ts; affectsProgramStructure: true, category: ts.Diagnostics.Editor_Support, description: ts.Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "disableSourceOfProjectReferenceRedirect", @@ -39273,7 +39464,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableSolutionSearching", @@ -39281,7 +39472,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "disableReferencedProjectLoad", @@ -39289,7 +39480,7 @@ var ts; isTSConfigOnly: true, category: ts.Diagnostics.Projects, description: ts.Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "noImplicitUseStrict", @@ -39297,7 +39488,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noEmitHelpers", @@ -39305,7 +39496,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "noEmitOnError", @@ -39314,7 +39505,7 @@ var ts; category: ts.Diagnostics.Emit, transpileOptionValue: undefined, description: ts.Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "preserveConstEnums", @@ -39322,7 +39513,7 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "declarationDir", @@ -39339,7 +39530,7 @@ var ts; type: "boolean", category: ts.Diagnostics.Completeness, description: ts.Diagnostics.Skip_type_checking_all_d_ts_files, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "allowUnusedLabels", @@ -39348,7 +39539,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unused_labels, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "allowUnreachableCode", @@ -39357,7 +39548,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Type_Checking, description: ts.Diagnostics.Disable_error_reporting_for_unreachable_code, - defaultValueDescription: "undefined" + defaultValueDescription: undefined, }, { name: "suppressExcessPropertyErrors", @@ -39365,7 +39556,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "suppressImplicitAnyIndexErrors", @@ -39373,7 +39564,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "forceConsistentCasingInFileNames", @@ -39381,7 +39572,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.Interop_Constraints, description: ts.Diagnostics.Ensure_that_casing_is_correct_in_imports, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "maxNodeModuleJsDepth", @@ -39389,7 +39580,7 @@ var ts; affectsModuleResolution: true, category: ts.Diagnostics.JavaScript_Support, description: ts.Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs, - defaultValueDescription: "0" + defaultValueDescription: 0, }, { name: "noStrictGenericChecks", @@ -39397,7 +39588,7 @@ var ts; affectsSemanticDiagnostics: true, category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types, - defaultValueDescription: "false" + defaultValueDescription: false, }, { name: "useDefineForClassFields", @@ -39414,14 +39605,14 @@ var ts; affectsEmit: true, category: ts.Diagnostics.Emit, description: ts.Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed, - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "keyofStringsOnly", type: "boolean", category: ts.Diagnostics.Backwards_Compatibility, description: ts.Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option, - defaultValueDescription: "false" + defaultValueDescription: false, }, { // A list of plugins to load in the language service @@ -39463,7 +39654,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Enable_verbose_logging, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "dry", @@ -39471,7 +39662,7 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "force", @@ -39479,14 +39670,14 @@ var ts; category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "clean", category: ts.Diagnostics.Command_line_Options, description: ts.Diagnostics.Delete_the_outputs_of_all_projects, type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, } ]; /* @internal */ @@ -39499,12 +39690,12 @@ var ts; */ name: "enableAutoDiscovery", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "enable", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, { name: "include", @@ -39525,7 +39716,7 @@ var ts; { name: "disableFilenameBasedTypeAcquisition", type: "boolean", - defaultValueDescription: "false", + defaultValueDescription: false, }, ]; /*@internal*/ @@ -41291,7 +41482,7 @@ var ts; ? 1 /* Recursive */ : 0 /* None */ }; } - if (ts.isImplicitGlob(spec)) { + if (ts.isImplicitGlob(spec.substring(spec.lastIndexOf(ts.directorySeparator) + 1))) { return { key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec), flags: 1 /* Recursive */ @@ -41657,7 +41848,8 @@ var ts; } } var failedLookupLocations = []; - var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: NodeResolutionFeatures.AllFeatures, conditions: ["node", "require", "types"] }; + var features = getDefaultNodeResolutionFeatures(options); + var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations, packageJsonInfoCache: cache, features: features, conditions: ["node", "require", "types"] }; var resolved = primaryLookup(); var primary = true; if (!resolved) { @@ -41741,6 +41933,34 @@ var ts; } } ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getDefaultNodeResolutionFeatures(options) { + return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 ? NodeResolutionFeatures.Node12Default : + ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext ? NodeResolutionFeatures.NodeNextDefault : + NodeResolutionFeatures.None; + } + /** + * @internal + * Does not try `@types/${packageName}` - use a second pass if needed. + */ + function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { + var moduleResolutionState = { + compilerOptions: options, + host: host, + traceEnabled: isTraceEnabled(options, host), + failedLookupLocations: [], + packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), + conditions: ts.emptyArray, + features: NodeResolutionFeatures.None, + }; + return ts.forEachAncestorDirectory(containingDirectory, function (ancestorDirectory) { + if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") { + var nodeModulesFolder = ts.combinePaths(ancestorDirectory, "node_modules"); + var candidate = ts.combinePaths(nodeModulesFolder, packageName); + return getPackageJsonInfo(candidate, /*onlyRecordFailures*/ false, moduleResolutionState); + } + }); + } + ts.resolvePackageNameToPackageJson = resolvePackageNameToPackageJson; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -42314,11 +42534,6 @@ var ts; } ts.resolveJSModule = resolveJSModule; /* @internal */ - function tryResolveJSModule(moduleName, initialDir, host) { - return tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule; - } - ts.tryResolveJSModule = tryResolveJSModule; - /* @internal */ var NodeResolutionFeatures; (function (NodeResolutionFeatures) { NodeResolutionFeatures[NodeResolutionFeatures["None"] = 0] = "None"; @@ -42332,13 +42547,15 @@ var ts; // not currently backported to node 12 - https://github.com/nodejs/Release/issues/690 NodeResolutionFeatures[NodeResolutionFeatures["ExportsPatternTrailers"] = 16] = "ExportsPatternTrailers"; NodeResolutionFeatures[NodeResolutionFeatures["AllFeatures"] = 30] = "AllFeatures"; + NodeResolutionFeatures[NodeResolutionFeatures["Node12Default"] = 14] = "Node12Default"; + NodeResolutionFeatures[NodeResolutionFeatures["NodeNextDefault"] = 30] = "NodeNextDefault"; NodeResolutionFeatures[NodeResolutionFeatures["EsmMode"] = 32] = "EsmMode"; })(NodeResolutionFeatures || (NodeResolutionFeatures = {})); function node12ModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Imports | NodeResolutionFeatures.SelfName | NodeResolutionFeatures.Exports, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.Node12Default, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { - return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.AllFeatures, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); + return nodeNextModuleNameResolverWorker(NodeResolutionFeatures.NodeNextDefault, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode); } function nodeNextModuleNameResolverWorker(features, moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var containingDirectory = ts.getDirectoryPath(containingFile); @@ -42624,6 +42841,97 @@ var ts; var versionPaths = packageInfo && packageInfo.versionPaths; return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } + /* @internal */ + function getEntrypointsFromPackageJsonInfo(packageJsonInfo, options, host, cache, resolveJs) { + if (!resolveJs && packageJsonInfo.resolvedEntrypoints !== undefined) { + // Cached value excludes resolutions to JS files - those could be + // cached separately, but they're used rarely. + return packageJsonInfo.resolvedEntrypoints; + } + var entrypoints; + var extensions = resolveJs ? Extensions.JavaScript : Extensions.TypeScript; + var features = getDefaultNodeResolutionFeatures(options); + var requireState = { + compilerOptions: options, + host: host, + traceEnabled: isTraceEnabled(options, host), + failedLookupLocations: [], + packageJsonInfoCache: cache === null || cache === void 0 ? void 0 : cache.getPackageJsonInfoCache(), + conditions: ["node", "require", "types"], + features: features, + }; + var requireResolution = loadNodeModuleFromDirectoryWorker(extensions, packageJsonInfo.packageDirectory, + /*onlyRecordFailures*/ false, requireState, packageJsonInfo.packageJsonContent, packageJsonInfo.versionPaths); + entrypoints = ts.append(entrypoints, requireResolution === null || requireResolution === void 0 ? void 0 : requireResolution.path); + if (features & NodeResolutionFeatures.Exports && packageJsonInfo.packageJsonContent.exports) { + for (var _i = 0, _a = [["node", "import", "types"], ["node", "require", "types"]]; _i < _a.length; _i++) { + var conditions = _a[_i]; + var exportState = __assign(__assign({}, requireState), { failedLookupLocations: [], conditions: conditions }); + var exportResolutions = loadEntrypointsFromExportMap(packageJsonInfo, packageJsonInfo.packageJsonContent.exports, exportState, extensions); + if (exportResolutions) { + for (var _b = 0, exportResolutions_1 = exportResolutions; _b < exportResolutions_1.length; _b++) { + var resolution = exportResolutions_1[_b]; + entrypoints = ts.appendIfUnique(entrypoints, resolution.path); + } + } + } + } + return packageJsonInfo.resolvedEntrypoints = entrypoints || false; + } + ts.getEntrypointsFromPackageJsonInfo = getEntrypointsFromPackageJsonInfo; + function loadEntrypointsFromExportMap(scope, exports, state, extensions) { + var entrypoints; + if (ts.isArray(exports)) { + for (var _i = 0, exports_1 = exports; _i < exports_1.length; _i++) { + var target = exports_1[_i]; + loadEntrypointsFromTargetExports(target); + } + } + // eslint-disable-next-line no-null/no-null + else if (typeof exports === "object" && exports !== null && allKeysStartWithDot(exports)) { + for (var key in exports) { + loadEntrypointsFromTargetExports(exports[key]); + } + } + else { + loadEntrypointsFromTargetExports(exports); + } + return entrypoints; + function loadEntrypointsFromTargetExports(target) { + var _a, _b; + if (typeof target === "string" && ts.startsWith(target, "./") && target.indexOf("*") === -1) { + var partsAfterFirst = ts.getPathComponents(target).slice(2); + if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + return false; + } + var resolvedTarget = ts.combinePaths(scope.packageDirectory, target); + var finalPath = ts.getNormalizedAbsolutePath(resolvedTarget, (_b = (_a = state.host).getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(_a)); + var result = loadJSOrExactTSFileName(extensions, finalPath, /*recordOnlyFailures*/ false, state); + if (result) { + entrypoints = ts.appendIfUnique(entrypoints, result, function (a, b) { return a.path === b.path; }); + return true; + } + } + else if (Array.isArray(target)) { + for (var _i = 0, target_1 = target; _i < target_1.length; _i++) { + var t = target_1[_i]; + var success = loadEntrypointsFromTargetExports(t); + if (success) { + return true; + } + } + } + // eslint-disable-next-line no-null/no-null + else if (typeof target === "object" && target !== null) { + return ts.forEach(ts.getOwnKeys(target), function (key) { + if (key === "default" || ts.contains(state.conditions, key) || isApplicableVersionedTypesKey(state.conditions, key)) { + loadEntrypointsFromTargetExports(target[key]); + return true; + } + }); + } + } + } /** * A function for locating the package.json scope for a given path */ @@ -42680,7 +42988,7 @@ var ts; trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); } var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); - var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths }; + var result = { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths, resolvedEntrypoints: undefined }; (_b = state.packageJsonInfoCache) === null || _b === void 0 ? void 0 : _b.setPackageJsonInfo(packageJsonPath, result); return result; } @@ -42977,8 +43285,8 @@ var ts; } return toSearchResult(/*value*/ undefined); } - for (var _d = 0, target_1 = target; _d < target_1.length; _d++) { - var elem = target_1[_d]; + for (var _d = 0, target_2 = target; _d < target_2.length; _d++) { + var elem = target_2[_d]; var result = loadModuleFromTargetImportOrExport(elem, subpath, pattern); if (result) { return result; @@ -43400,14 +43708,12 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); ts.performance.measure("Bind", "beforeBind", "afterBind"); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } ts.bindSourceFile = bindSourceFile; function createBinder() { @@ -43467,7 +43773,9 @@ var ts; ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true); bind(file); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); file.symbolCount = symbolCount; file.classifiableNames = classifiableNames; delayedBindJSDocTypedefTag(); @@ -44507,7 +44815,7 @@ var ts; maybeBindExpressionFlowIfCall(node.expression); } function maybeBindExpressionFlowIfCall(node) { - // A top level or LHS of comma expression call expression with a dotted function name and at least one argument + // A top level or comma expression call expression with a dotted function name and at least one argument // is potentially an assertion and is therefore included in the control flow. if (node.kind === 207 /* CallExpression */) { var call = node; @@ -44675,22 +44983,27 @@ var ts; } return state; } - function onLeft(left, state, _node) { + function onLeft(left, state, node) { if (!state.skip) { - return maybeBind(left); + var maybeBound = maybeBind(left); + if (node.operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(left); + } + return maybeBound; } } - function onOperator(operatorToken, state, node) { + function onOperator(operatorToken, state, _node) { if (!state.skip) { - if (operatorToken.kind === 27 /* CommaToken */) { - maybeBindExpressionFlowIfCall(node.left); - } bind(operatorToken); } } - function onRight(right, state, _node) { + function onRight(right, state, node) { if (!state.skip) { - return maybeBind(right); + var maybeBound = maybeBind(right); + if (node.operatorToken.kind === 27 /* CommaToken */) { + maybeBindExpressionFlowIfCall(right); + } + return maybeBound; } } function onExit(node, state) { @@ -45141,10 +45454,6 @@ var ts; seen.set(identifier.escapedText, currentKind); continue; } - if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) { - var span = ts.getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } } } return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */); @@ -45378,7 +45687,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { + if (languageVersion < 1 /* ES5 */ && inStrictMode && node.numericLiteralFlags & 32 /* Octal */) { file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -45437,6 +45746,8 @@ var ts; return; } ts.setParent(node, parent); + if (ts.tracing) + node.tracingPath = file.path; var saveInStrictMode = inStrictMode; // Even though in the AST the jsdoc @typedef node belongs to the current node, // its symbol might be in the same scope with the current node's symbol. Consider: @@ -46257,7 +46568,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (!ts.isBindingPattern(node.name)) { - if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node) && !ts.getJSDocTypeTag(node)) { + if (ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !ts.getJSDocTypeTag(node)) { declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */); } else if (ts.isBlockOrCatchScoped(node)) { @@ -46768,6 +47079,9 @@ var ts; TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts"; TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE"; TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts"; + // Masks + TypeFacts[TypeFacts["OrFactsMask"] = 8256] = "OrFactsMask"; + TypeFacts[TypeFacts["AndFactsMask"] = 16768959] = "AndFactsMask"; })(TypeFacts || (TypeFacts = {})); var typeofEQFacts = new ts.Map(ts.getEntries({ string: 1 /* TypeofEQString */, @@ -46808,6 +47122,9 @@ var ts; CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive"; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; + CheckMode[CheckMode["RestBindingElement"] = 32] = "RestBindingElement"; + // e.g. in `const { a, ...rest } = foo`, when checking the type of `foo` to determine the type of `rest`, + // we need to preserve generic types instead of substituting them for constraints })(CheckMode || (CheckMode = {})); var SignatureCheckMode; (function (SignatureCheckMode) { @@ -46823,8 +47140,7 @@ var ts; IntersectionState[IntersectionState["Source"] = 1] = "Source"; IntersectionState[IntersectionState["Target"] = 2] = "Target"; IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck"; - IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck"; - IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck"; + IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck"; })(IntersectionState || (IntersectionState = {})); var RecursionFlags; (function (RecursionFlags) { @@ -47021,6 +47337,7 @@ var ts; var location = ts.getParseTreeNode(locationIn); return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType; }, + getTypeOfSymbol: getTypeOfSymbol, getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) { var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter); if (parameter === undefined) @@ -47044,6 +47361,7 @@ var ts; getIndexInfosOfType: getIndexInfosOfType, getSignaturesOfType: getSignaturesOfType, getIndexTypeOfType: function (type, kind) { return getIndexTypeOfType(type, kind === 0 /* String */ ? stringType : numberType); }, + getIndexType: function (type) { return getIndexType(type); }, getBaseTypes: getBaseTypes, getBaseTypeOfLiteralType: getBaseTypeOfLiteralType, getWidenedType: getWidenedType, @@ -47726,6 +48044,9 @@ var ts; suggestionDiagnostics.add(diagnostic); return diagnostic; } + function isDeprecatedSymbol(symbol) { + return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 134217728 /* Deprecated */); + } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity); return addDeprecatedSuggestionWorker(declarations, diagnostic); @@ -47855,13 +48176,13 @@ var ts; else { // error var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); - var message = isEitherEnum - ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations - : isEitherBlockScoped_1 - ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 + var message = isEitherEnum ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations + : isEitherBlockScoped_1 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]); var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]); + var isSourcePlainJs = ts.isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs); + var isTargetPlainJs = ts.isPlainJsFile(targetSymbolFile, compilerOptions.checkJs); var symbolName_1 = symbolToString(source); // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { @@ -47873,12 +48194,16 @@ var ts; var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () { return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] }); }); - addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); - addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + if (!isSourcePlainJs) + addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); + if (!isTargetPlainJs) + addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); } else { - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); + if (!isSourcePlainJs) + addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target); + if (!isTargetPlainJs) + addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source); } } return target; @@ -48301,11 +48626,12 @@ var ts; * * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters. */ - function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals) { + function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions) { if (excludeGlobals === void 0) { excludeGlobals = false; } - return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol); + if (getSpellingSuggstions === void 0) { getSpellingSuggstions = true; } + return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggstions, getSymbol); } - function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup) { + function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSpellingSuggestions, lookup) { var _a, _b, _c; var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location var result; @@ -48334,6 +48660,8 @@ var ts; // type parameters are visible in parameter list, return type and type parameter list ? lastLocation === location.type || lastLocation.kind === 163 /* Parameter */ || + lastLocation.kind === 338 /* JSDocParameterTag */ || + lastLocation.kind === 339 /* JSDocReturnTag */ || lastLocation.kind === 162 /* TypeParameter */ // local types not visible outside the function body : false; @@ -48593,9 +48921,9 @@ var ts; lastSelfReferenceLocation = location; } lastLocation = location; - location = ts.isJSDocTemplateTag(location) ? - ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent : - location.parent; + location = ts.isJSDocTemplateTag(location) ? ts.getEffectiveContainerForJSDocTemplateTag(location) || location.parent : + ts.isJSDocParameterTag(location) || ts.isJSDocReturnTag(location) ? ts.getHostSignatureFromJSDoc(location) || location.parent : + location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. @@ -48622,7 +48950,7 @@ var ts; } } if (!result) { - if (nameNotFoundMessage) { + if (nameNotFoundMessage && produceDiagnostics) { if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 !checkAndReportErrorForExtendingInterface(errorLocation) && @@ -48632,7 +48960,7 @@ var ts; !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { var suggestion = void 0; - if (suggestionCount < maximumSuggestionCount) { + if (getSpellingSuggestions && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); var isGlobalScopeAugmentationDeclaration = (suggestion === null || suggestion === void 0 ? void 0 : suggestion.valueDeclaration) && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration); if (isGlobalScopeAugmentationDeclaration) { @@ -48668,7 +48996,7 @@ var ts; return undefined; } // Perform extra checks only if error reporting was requested - if (nameNotFoundMessage) { + if (nameNotFoundMessage && produceDiagnostics) { if (propertyWithInvalidInitializer && !(ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields)) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed @@ -48716,24 +49044,19 @@ var ts; error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation)); } } - if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) { - checkSymbolUsageInExpressionContext(result, name, errorLocation); + if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */ && !(result.flags & 111551 /* Value */) && !ts.isValidTypeOnlyAliasUseSite(errorLocation)) { + var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(result); + if (typeOnlyDeclaration) { + var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ + ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type + : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; + var unescapedName = ts.unescapeLeadingUnderscores(name); + addTypeOnlyDeclarationRelatedInfo(error(errorLocation, message, unescapedName), typeOnlyDeclaration, unescapedName); + } } } return result; } - function checkSymbolUsageInExpressionContext(symbol, name, useSite) { - if (!ts.isValidTypeOnlyAliasUseSite(useSite)) { - var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol); - if (typeOnlyDeclaration) { - var message = typeOnlyDeclaration.kind === 274 /* ExportSpecifier */ - ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type - : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type; - var unescapedName = ts.unescapeLeadingUnderscores(name); - addTypeOnlyDeclarationRelatedInfo(error(useSite, message, unescapedName), typeOnlyDeclaration, unescapedName); - } - } - } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { if (!typeOnlyDeclaration) return diagnostic; @@ -48981,10 +49304,12 @@ var ts; } /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached. * If at any point current node is equal to 'parent' node - return true. + * If current node is an IIFE, continue walking up. * Return false if 'stopAt' node is reached or isFunctionLike(current) === true. */ function isSameScopeDescendentOf(initial, parent, stopAt) { - return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; }); + return !!parent && !!ts.findAncestor(initial, function (n) { return n === parent + || (n === stopAt || ts.isFunctionLike(n) && !ts.getImmediatelyInvokedFunctionExpression(n) ? "quit" : false); }); } function getAnyImportSyntax(node) { switch (node.kind) { @@ -49035,7 +49360,7 @@ var ts; && isAliasableOrJsExpression(node.parent.right) || node.kind === 295 /* ShorthandPropertyAssignment */ || node.kind === 294 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer) - || ts.isRequireVariableDeclaration(node); + || ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node); } function isAliasableOrJsExpression(e) { return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e); @@ -49732,16 +50057,20 @@ var ts; return; } var host = ts.getJSDocHost(node); - if (host && - ts.isExpressionStatement(host) && - ts.isBinaryExpression(host.expression) && - ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) { - // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + if (host && ts.isExpressionStatement(host) && ts.isPrototypePropertyAssignment(host.expression)) { + // /** @param {K} p */ X.prototype.m = function () { } <-- look for K on X's declaration var symbol = getSymbolOfNode(host.expression.left); if (symbol) { return getDeclarationOfJSPrototypeContainer(symbol); } } + if (host && ts.isFunctionExpression(host) && ts.isPrototypePropertyAssignment(host.parent) && ts.isExpressionStatement(host.parent.parent)) { + // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration + var symbol = getSymbolOfNode(host.parent.left); + if (symbol) { + return getDeclarationOfJSPrototypeContainer(symbol); + } + } if (host && (ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) && ts.isBinaryExpression(host.parent.parent) && ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) { @@ -49823,8 +50152,14 @@ var ts; var mode = contextSpecifier && ts.isStringLiteralLike(contextSpecifier) ? ts.getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat; var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference, mode); var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule); - var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); + var sourceFile = resolvedModule + && (!resolutionDiagnostic || resolutionDiagnostic === ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) + && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { + // If there's a resolutionDiagnostic we need to report it even if a sourceFile is found. + if (resolutionDiagnostic) { + error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); + } if (sourceFile.symbol) { if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); @@ -50006,7 +50341,7 @@ var ts; if (!sigs || !sigs.length) { sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); } - if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */)) { + if ((sigs && sigs.length) || getPropertyOfType(type, "default" /* Default */, /*skipObjectFunctionPropertyAugment*/ true)) { var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol, reference); return cloneTypeAsModuleType(symbol, moduleType, referenceParent); } @@ -50966,6 +51301,7 @@ var ts; getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; }, getCurrentDirectory: function () { return host.getCurrentDirectory(); }, getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache), + getPackageJsonInfoCache: function () { var _a; return (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host); }, useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), redirectTargetsMap: host.redirectTargetsMap, getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); }, @@ -51144,7 +51480,7 @@ var ts; context.approximateLength += 6; return ts.factory.createKeywordTypeNode(147 /* ObjectKeyword */); } - if (isThisTypeParameter(type)) { + if (ts.isThisTypeParameter(type)) { if (context.flags & 4194304 /* InObjectTypeLiteral */) { if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; @@ -51836,8 +52172,8 @@ var ts; var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0]; // If the expanded parameter list had a variadic in a non-trailing position, don't expand it var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 170 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); }); - if (signature.thisParameter) { - var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); + var thisParameter = tryGetThisParameterDeclaration(signature, context); + if (thisParameter) { parameters.unshift(thisParameter); } var returnTypeNode; @@ -51886,6 +52222,21 @@ var ts; } return node; } + function tryGetThisParameterDeclaration(signature, context) { + if (signature.thisParameter) { + return symbolToParameterDeclaration(signature.thisParameter, context); + } + if (signature.declaration) { + var thisTag = ts.getJSDocThisTag(signature.declaration); + if (thisTag && thisTag.typeExpression) { + return ts.factory.createParameterDeclaration( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, "this", + /* questionToken */ undefined, typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context)); + } + } + } function typeParameterToDeclarationWithConstraint(type, context, constraintNode) { var savedContextFlags = context.flags; context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic @@ -52195,8 +52546,8 @@ var ts; } else { if (parent && getExportsOfSymbol(parent)) { - var exports_1 = getExportsOfSymbol(parent); - ts.forEachEntry(exports_1, function (ex, name) { + var exports_2 = getExportsOfSymbol(parent); + ts.forEachEntry(exports_2, function (ex, name) { if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) { symbolName = ts.unescapeLeadingUnderscores(name); return true; @@ -52327,10 +52678,8 @@ var ts; firstChar = symbolName.charCodeAt(0); } var expression = void 0; - if (ts.isSingleOrDoubleQuote(firstChar)) { - expression = ts.factory.createStringLiteral(symbolName - .substring(1, symbolName.length - 1) - .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */); + if (ts.isSingleOrDoubleQuote(firstChar) && !(symbol.flags & 8 /* EnumMember */)) { + expression = ts.factory.createStringLiteral(ts.stripQuotes(symbolName).replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */); } else if (("" + +symbolName) === symbolName) { expression = ts.factory.createNumericLiteral(+symbolName); @@ -52359,7 +52708,7 @@ var ts; } var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName); var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed); - return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote); + return ts.createPropertyNameNodeForIdentifierOrLiteral(rawName, ts.getEmitScriptTarget(compilerOptions), singleQuote, stringNamed); } // See getNameForSymbolFromNameType for a stringy equivalent function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) { @@ -52367,24 +52716,19 @@ var ts; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; - if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) { + if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !ts.isNumericLiteralName(name)) { return ts.factory.createStringLiteral(name, !!singleQuote); } - if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { + if (ts.isNumericLiteralName(name) && ts.startsWith(name, "-")) { return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name)); } - return createPropertyNameNodeForIdentifierOrLiteral(name); + return ts.createPropertyNameNodeForIdentifierOrLiteral(name, ts.getEmitScriptTarget(compilerOptions)); } if (nameType.flags & 8192 /* UniqueESSymbol */) { return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */)); } } } - function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) { - return ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) ? ts.factory.createIdentifier(name) : - !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) : - ts.factory.createStringLiteral(name, !!singleQuote); - } function cloneNodeBuilderContext(context) { var initial = __assign({}, context); // Make type parameters created within this context not consume the name outside this context @@ -52478,7 +52822,8 @@ var ts; includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym); } if (ts.isIdentifier(node)) { - var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node); + var type = getDeclaredTypeOfSymbol(sym); + var name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : ts.factory.cloneNode(node); name.symbol = sym; // for quickinfo, which uses identifier symbol information return { introducesError: introducesError, node: ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } @@ -53900,10 +54245,10 @@ var ts; if (nameType) { if (nameType.flags & 384 /* StringOrNumberLiteral */) { var name = "" + nameType.value; - if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !isNumericLiteralName(name)) { + if (!ts.isIdentifierText(name, ts.getEmitScriptTarget(compilerOptions)) && !ts.isNumericLiteralName(name)) { return "\"".concat(ts.escapeString(name, 34 /* doubleQuote */), "\""); } - if (isNumericLiteralName(name) && ts.startsWith(name, "-")) { + if (ts.isNumericLiteralName(name) && ts.startsWith(name, "-")) { return "[".concat(name, "]"); } return name; @@ -54212,9 +54557,12 @@ var ts; } // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. - function getTypeForBindingElementParent(node) { + function getTypeForBindingElementParent(node, checkMode) { + if (checkMode !== 0 /* Normal */) { + return getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false, checkMode); + } var symbol = getSymbolOfNode(node); - return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false); + return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false, checkMode); } function getRestType(source, properties, symbol) { source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); }); @@ -54225,7 +54573,27 @@ var ts; return mapType(source, function (t) { return getRestType(t, properties, symbol); }); } var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName)); + var spreadableProperties = []; + var unspreadableToRestKeys = []; + for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { + var prop = _a[_i]; + var literalTypeFromProperty = getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */); + if (!isTypeAssignableTo(literalTypeFromProperty, omitKeyType) + && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) + && isSpreadableProperty(prop)) { + spreadableProperties.push(prop); + } + else { + unspreadableToRestKeys.push(literalTypeFromProperty); + } + } if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) { + if (unspreadableToRestKeys.length) { + // If the type we're spreading from has properties that cannot + // be spread into the rest type (e.g. getters, methods), ensure + // they are explicitly omitted, as they would in the non-generic case. + omitKeyType = getUnionType(__spreadArray([omitKeyType], unspreadableToRestKeys, true)); + } if (omitKeyType.flags & 131072 /* Never */) { return source; } @@ -54236,13 +54604,9 @@ var ts; return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]); } var members = ts.createSymbolTable(); - for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) { - var prop = _a[_i]; - if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType) - && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) - && isSpreadableProperty(prop)) { - members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false)); - } + for (var _b = 0, spreadableProperties_1 = spreadableProperties; _b < spreadableProperties_1.length; _b++) { + var prop = spreadableProperties_1[_b]; + members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false)); } var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfosOfType(source)); result.objectFlags |= 8388608 /* ObjectRestType */; @@ -54316,12 +54680,16 @@ var ts; } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { - var pattern = declaration.parent; - var parentType = getTypeForBindingElementParent(pattern.parent); - // If no type or an any type was inferred for parent, infer that for the binding element - if (!parentType || isTypeAny(parentType)) { + var checkMode = declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + var parentType = getTypeForBindingElementParent(declaration.parent.parent, checkMode); + return parentType && getBindingElementTypeFromParentType(declaration, parentType); + } + function getBindingElementTypeFromParentType(declaration, parentType) { + // If an any type was inferred for parent, infer that for the binding element + if (isTypeAny(parentType)) { return parentType; } + var pattern = declaration.parent; // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); @@ -54385,9 +54753,9 @@ var ts; if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) { // In strict null checking mode, if a default value of a non-undefined type is specified, remove // undefined from the final type. - return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; + return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration, 0 /* Normal */)) & 32768 /* Undefined */) ? getNonUndefinedType(type) : type; } - return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration)], 2 /* Subtype */)); + return widenTypeInferredFromInitializer(declaration, getUnionType([getNonUndefinedType(type), checkDeclarationInitializer(declaration, 0 /* Normal */)], 2 /* Subtype */)); } function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); @@ -54410,11 +54778,11 @@ var ts; return strictNullChecks && isOptional ? getOptionalType(type, isProperty) : type; } // Return the inferred type for a variable, parameter, or property declaration - function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { + function getTypeForVariableLikeDeclaration(declaration, includeOptionality, checkMode) { // A variable declared in a for..in statement is of type string, or of type keyof T when the // right hand expression is of a type parameter type. if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 242 /* ForInStatement */) { - var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression))); + var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression, /*checkMode*/ checkMode))); return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType; } if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 243 /* ForOfStatement */) { @@ -54469,12 +54837,9 @@ var ts; } } if (ts.isInJSFile(declaration)) { - var typeTag = ts.getJSDocType(func); - if (typeTag && ts.isFunctionTypeNode(typeTag)) { - var signature = getSignatureFromDeclaration(typeTag); - var pos = func.parameters.indexOf(declaration); - return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); - } + var type_1 = getParameterTypeOfTypeTag(func, declaration); + if (type_1) + return type_1; } // Use contextual parameter type if one is available var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); @@ -54491,7 +54856,7 @@ var ts; return containerObjectType; } } - var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration)); + var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration, checkMode)); return addOptionality(type, isProperty, isOptional); } if (ts.isPropertyDeclaration(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) { @@ -54863,7 +55228,7 @@ var ts; // contextual type or, if the element itself is a binding pattern, with the type implied by that binding // pattern. var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType; - return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType))); + return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); } if (ts.isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors); @@ -54952,7 +55317,7 @@ var ts; // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string. function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { - return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors); + return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true, 0 /* Normal */), declaration, reportErrors); } function isGlobalSymbolConstructor(node) { var symbol = getSymbolOfNode(node); @@ -55041,9 +55406,9 @@ var ts; if (typeNode === undefined) { return useUnknownInCatchVariables ? unknownType : anyType; } - var type_1 = getTypeOfNode(typeNode); + var type_2 = getTypeOfNode(typeNode); // an errorType will make `checkTryStatement` issue an error - return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType; + return isTypeAny(type_2) || type_2 === unknownType ? type_2 : errorType; } // Handle export default expressions if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { @@ -55181,10 +55546,12 @@ var ts; if (writing === void 0) { writing = false; } var getter = ts.getDeclarationOfKind(symbol, 171 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 172 /* SetAccessor */); - var setterType = getAnnotatedAccessorType(setter); // For write operations, prioritize type annotations on the setter - if (writing && setterType) { - return instantiateTypeIfNeeded(setterType, symbol); + if (writing) { + var setterType_1 = getAnnotatedAccessorType(setter); + if (setterType_1) { + return instantiateTypeIfNeeded(setterType_1, symbol); + } } // Else defer to the getter type if (getter && ts.isInJSFile(getter)) { @@ -55199,6 +55566,7 @@ var ts; return instantiateTypeIfNeeded(getterType, symbol); } // If the user didn't specify a return type, try to use the set-accessor's parameter type. + var setterType = getAnnotatedAccessorType(setter); if (setterType) { return setterType; } @@ -55269,11 +55637,11 @@ var ts; return errorType; } var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */)); - var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + var type_3 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } - return type_2; + return type_3; } } var type = createObjectType(16 /* Anonymous */, symbol); @@ -55347,6 +55715,39 @@ var ts; } return links.type; } + function getWriteTypeOfSymbolWithDeferredType(symbol) { + var links = getSymbolLinks(symbol); + if (!links.writeType && links.deferralWriteConstituents) { + ts.Debug.assertIsDefined(links.deferralParent); + ts.Debug.assertIsDefined(links.deferralConstituents); + links.writeType = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralWriteConstituents) : getIntersectionType(links.deferralWriteConstituents); + } + return links.writeType; + } + /** + * Distinct write types come only from set accessors, but union and intersection + * properties deriving from set accessors will either pre-compute or defer the + * union or intersection of the writeTypes of their constituents. To account for + * this, we will assume that any deferred type or transient symbol may have a + * `writeType` (or a deferred write type ready to be computed) that should be + * used before looking for set accessor declarations. + */ + function getWriteTypeOfSymbol(symbol) { + var checkFlags = ts.getCheckFlags(symbol); + if (checkFlags & 65536 /* DeferredType */) { + var writeType = getWriteTypeOfSymbolWithDeferredType(symbol); + if (writeType) { + return writeType; + } + } + if (symbol.flags & 33554432 /* Transient */) { + var writeType = symbol.writeType; + if (writeType) { + return writeType; + } + } + return getSetAccessorTypeOfSymbol(symbol); + } function getSetAccessorTypeOfSymbol(symbol) { if (symbol.flags & 98304 /* Accessor */) { var type = getTypeOfSetAccessor(symbol); @@ -55544,7 +55945,8 @@ var ts; return false; } function getBaseTypeNodeOfClass(type) { - return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration); + var decl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + return decl && ts.getEffectiveBaseTypeNode(decl); } function getConstructorsForTypeArguments(type, typeArgumentNodes, location) { var typeArgCount = ts.length(typeArgumentNodes); @@ -55566,8 +55968,8 @@ var ts; */ function getBaseConstructorTypeOfClass(type) { if (!type.resolvedBaseConstructorType) { - var decl = type.symbol.valueDeclaration; - var extended = ts.getEffectiveBaseTypeNode(decl); + var decl = ts.getClassLikeDeclarationOfSymbol(type.symbol); + var extended = decl && ts.getEffectiveBaseTypeNode(decl); var baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; @@ -57294,6 +57696,11 @@ var ts; return simplified !== type ? simplified : getConstraintOfType(type); } function getConstraintFromIndexedAccess(type) { + if (isMappedTypeGenericIndexedAccess(type)) { + // For indexed access types of the form { [P in K]: E }[X], where K is non-generic and X is generic, + // we substitute an instantiation of E where P is replaced with X. + return substituteIndexedMappedType(type.objectType, type.indexType); + } var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType); if (indexConstraint && indexConstraint !== type.indexType) { var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.accessFlags); @@ -57466,10 +57873,10 @@ var ts; var baseTypes = []; var different = false; for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { - var type_3 = types_7[_i]; - var baseType = getBaseConstraint(type_3); + var type_4 = types_7[_i]; + var baseType = getBaseConstraint(type_4); if (baseType) { - if (baseType !== type_3) { + if (baseType !== type_4) { different = true; } baseTypes.push(baseType); @@ -57498,6 +57905,11 @@ var ts; return constraint ? getStringMappingType(t.symbol, constraint) : stringType; } if (t.flags & 8388608 /* IndexedAccess */) { + if (isMappedTypeGenericIndexedAccess(t)) { + // For indexed access types of the form { [P in K]: E }[X], where K is non-generic and X is generic, + // we substitute an instantiation of E where P is replaced with X. + return getBaseConstraint(substituteIndexedMappedType(t.objectType, t.indexType)); + } var baseObjectType = getBaseConstraint(t.objectType); var baseIndexType = getBaseConstraint(t.indexType); var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.accessFlags); @@ -57572,13 +57984,17 @@ var ts; } return type; } + function isMappedTypeGenericIndexedAccess(type) { + return type.flags & 8388608 /* IndexedAccess */ && ts.getObjectFlags(type.objectType) & 32 /* Mapped */ && + !isGenericMappedType(type.objectType) && isGenericIndexType(type.indexType); + } /** * For a type parameter, return the base constraint of the type parameter. For the string, number, * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the * type itself. */ function getApparentType(type) { - var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type; + var t = !(type.flags & 465829888 /* Instantiable */) ? type : getBaseConstraintOfType(type) || unknownType; return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) : t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) : t.flags & 402653316 /* StringLike */ ? globalStringType : @@ -57702,6 +58118,7 @@ var ts; var firstType; var nameType; var propTypes = []; + var writeTypes; var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _d = 0, props_1 = props; _d < props_1.length; _d++) { @@ -57718,6 +58135,10 @@ var ts; firstType = type; nameType = getSymbolLinks(prop).nameType; } + var writeType = getWriteTypeOfSymbol(prop); + if (writeTypes || writeType !== type) { + writeTypes = ts.append(!writeTypes ? propTypes.slice() : writeTypes, writeType); + } else if (type !== firstType) { checkFlags |= 64 /* HasNonUniformType */; } @@ -57746,9 +58167,13 @@ var ts; result.checkFlags |= 65536 /* DeferredType */; result.deferralParent = containingType; result.deferralConstituents = propTypes; + result.deferralWriteConstituents = writeTypes; } else { result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); + if (writeTypes) { + result.writeType = isUnion ? getUnionType(writeTypes) : getIntersectionType(writeTypes); + } } return result; } @@ -57916,7 +58341,7 @@ var ts; // signature applies to types assignable to 'number' and numeric string literal types. return isTypeAssignableTo(source, target) || target === stringType && isTypeAssignableTo(source, numberType) || - target === numberType && !!(source.flags & 128 /* StringLiteral */) && isNumericLiteralName(source.value); + target === numberType && !!(source.flags & 128 /* StringLiteral */) && ts.isNumericLiteralName(source.value); } function getIndexInfosOfStructuredType(type) { if (type.flags & 3670016 /* StructuredType */) { @@ -58164,6 +58589,13 @@ var ts; var typeTag = ts.getJSDocTypeTag(node); return (typeTag === null || typeTag === void 0 ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } + function getParameterTypeOfTypeTag(func, parameter) { + var signature = getSignatureOfTypeTag(func); + if (!signature) + return undefined; + var pos = func.parameters.indexOf(parameter); + return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); + } function getReturnTypeOfTypeTag(node) { var signature = getSignatureOfTypeTag(node); return signature && getReturnTypeOfSignature(signature); @@ -58194,6 +58626,8 @@ var ts; case 205 /* PropertyAccessExpression */: case 206 /* ElementAccessExpression */: return traverse(node.expression); + case 294 /* PropertyAssignment */: + return traverse(node.initializer); default: return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse); } @@ -58888,7 +59322,7 @@ var ts; } function getImpliedConstraint(type, checkNode, extendsNode) { return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) : - getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) : + getActualTypeVariable(getTypeFromTypeNode(checkNode)) === getActualTypeVariable(type) ? getTypeFromTypeNode(extendsNode) : undefined; } function getConditionalFlowTypeOfType(type, node) { @@ -59073,7 +59507,7 @@ var ts; } function getGlobalSymbol(name, meaning, diagnostic) { // Don't track references for global symbols anyway, so value if `isReference` is arbitrary - return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false); + return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ false); } function getGlobalType(name, arity, reportErrors) { var symbol = getGlobalTypeSymbol(name, reportErrors); @@ -60458,7 +60892,7 @@ var ts; } var prop = getPropertyOfType(objectType, propName); if (prop) { - if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) { + if (accessFlags & 64 /* ReportDeprecated */ && accessNode && prop.declarations && isDeprecatedSymbol(prop) && isUncalledFunctionReference(accessNode, prop)) { var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode); addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName); } @@ -60480,7 +60914,7 @@ var ts; getFlowTypeOfReference(accessExpression, propType) : propType; } - if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { + if (everyType(objectType, isTupleType) && ts.isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 16 /* NoTupleBoundsCheck */)) { var indexNode = getIndexNodeForAccessExpression(accessNode); if (isTupleType(objectType)) { @@ -60652,9 +61086,6 @@ var ts; return (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type) || isGenericTupleType(type) ? 8388608 /* IsGenericObjectType */ : 0) | (type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && !isPatternLiteralType(type) ? 16777216 /* IsGenericIndexType */ : 0); } - function isThisTypeParameter(type) { - return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType); - } function getSimplifiedType(type, writing) { return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) : type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) : @@ -60768,7 +61199,7 @@ var ts; return everyType(indexType, function (t) { if (t.flags & 384 /* StringOrNumberLiteral */) { var propName = getPropertyNameFromType(t); - if (isNumericLiteralName(propName)) { + if (ts.isNumericLiteralName(propName)) { var index = +propName; return index >= 0 && index < limit; } @@ -61298,7 +61729,7 @@ var ts; var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */); var result = createSymbol(flags, leftProp.escapedName); - result.type = getUnionType([getTypeOfSymbol(leftProp), removeMissingOrUndefinedType(rightType)]); + result.type = getUnionType([getTypeOfSymbol(leftProp), removeMissingOrUndefinedType(rightType)], 2 /* Subtype */); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; @@ -62943,7 +63374,7 @@ var ts; return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var related = relation.get(getRelationKey(source, target, 0 /* None */, relation)); + var related = relation.get(getRelationKey(source, target, 0 /* None */, relation, /*ignoreConstraints*/ false)); if (related !== undefined) { return !!(related & 1 /* Succeeded */); } @@ -62995,11 +63426,11 @@ var ts; var overflow = false; var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid var lastSkippedInfo; - var incompatibleStack = []; + var incompatibleStack; var inPropertyCheck = false; ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); var result = isRelatedTo(source, target, 3 /* Both */, /*reportErrors*/ !!errorNode, headMessage); - if (incompatibleStack.length) { + if (incompatibleStack) { reportIncompatibleStack(); } if (overflow) { @@ -63056,19 +63487,19 @@ var ts; return { errorInfo: errorInfo, lastSkippedInfo: lastSkippedInfo, - incompatibleStack: incompatibleStack.slice(), + incompatibleStack: incompatibleStack === null || incompatibleStack === void 0 ? void 0 : incompatibleStack.slice(), overrideNextErrorInfo: overrideNextErrorInfo, - relatedInfo: !relatedInfo ? undefined : relatedInfo.slice() + relatedInfo: relatedInfo === null || relatedInfo === void 0 ? void 0 : relatedInfo.slice(), }; } function reportIncompatibleError(message, arg0, arg1, arg2, arg3) { overrideNextErrorInfo++; // Suppress the next relation error lastSkippedInfo = undefined; // Reset skipped info cache - incompatibleStack.push([message, arg0, arg1, arg2, arg3]); + (incompatibleStack || (incompatibleStack = [])).push([message, arg0, arg1, arg2, arg3]); } function reportIncompatibleStack() { - var stack = incompatibleStack; - incompatibleStack = []; + var stack = incompatibleStack || []; + incompatibleStack = undefined; var info = lastSkippedInfo; lastSkippedInfo = undefined; if (stack.length === 1) { @@ -63174,7 +63605,7 @@ var ts; } function reportError(message, arg0, arg1, arg2, arg3) { ts.Debug.assert(!!errorNode); - if (incompatibleStack.length) + if (incompatibleStack) reportIncompatibleStack(); if (message.elidedInCompatabilityPyramid) return; @@ -63190,7 +63621,7 @@ var ts; } } function reportRelationError(message, source, target) { - if (incompatibleStack.length) + if (incompatibleStack) reportIncompatibleStack(); var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1]; var generalizedSource = source; @@ -63302,7 +63733,9 @@ var ts; if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) { return -1 /* True */; } - reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 2048 /* JsxAttributes */)); + if (reportErrors) { + reportErrorResults(originalSource, originalTarget, originalSource, originalTarget, headMessage); + } return 0 /* False */; } // Normalize the source and target types: Turn fresh literal types into regular literal types, @@ -63314,7 +63747,12 @@ var ts; if (source === target) return -1 /* True */; if (relation === identityRelation) { - return isIdenticalTo(source, target, recursionFlags); + if (source.flags !== target.flags) + return 0 /* False */; + if (source.flags & 67358815 /* Singleton */) + return -1 /* True */; + traceUnionsOrIntersectionsTooLarge(source, target); + return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags); } // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common, // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself, @@ -63324,163 +63762,130 @@ var ts; if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) { return -1 /* True */; } - // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`. - // If so, reporting the `null` and `undefined` in the type is hardly useful. - // First, see if we're even relating an object type to a union. - // Then see if the target is stripped down to a single non-union type. - // Note - // * We actually want to remove null and undefined naively here (rather than using getNonNullableType), - // since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`" - // when dealing with generics. - // * We also don't deal with primitive source types, since we already halt elaboration below. - if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ && - target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) { - var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */); - if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) { - target = getNormalizedType(nullStrippedTarget, /*writing*/ true); - } - if (source === nullStrippedTarget) - return -1 /* True */; + // See if we're relating a definitely non-nullable type to a union that includes null and/or undefined + // plus a single non-nullable type. If so, remove null and/or undefined from the target type. + if (source.flags & 470302716 /* DefinitelyNonNullable */ && target.flags & 1048576 /* Union */) { + var types = target.types; + var candidate = types.length === 2 && types[0].flags & 98304 /* Nullable */ ? types[1] : + types.length === 3 && types[0].flags & 98304 /* Nullable */ && types[1].flags & 98304 /* Nullable */ ? types[2] : + undefined; + if (candidate && !(candidate.flags & 98304 /* Nullable */)) { + target = getNormalizedType(candidate, /*writing*/ true); + if (source === target) + return -1 /* True */; + } } if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined)) return -1 /* True */; - var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); - var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); - if (isPerformingExcessPropertyChecks) { - if (hasExcessProperties(source, target, reportErrors)) { + if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) { + var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 16384 /* FreshLiteral */); + if (isPerformingExcessPropertyChecks) { + if (hasExcessProperties(source, target, reportErrors)) { + if (reportErrors) { + reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target); + } + return 0 /* False */; + } + } + var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) && + source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && + target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && + (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)); + var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 2048 /* JsxAttributes */); + if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) { if (reportErrors) { - reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target); + var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source); + var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target); + var calls = getSignaturesOfType(source, 0 /* Call */); + var constructs = getSignaturesOfType(source, 1 /* Construct */); + if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) || + constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) { + reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); + } + else { + reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); + } } return 0 /* False */; } - } - var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) && - source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType && - target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) && - (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source)); - if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) { - if (reportErrors) { - var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source); - var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target); - var calls = getSignaturesOfType(source, 0 /* Call */); - var constructs = getSignaturesOfType(source, 1 /* Construct */); - if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, 1 /* Source */, /*reportErrors*/ false) || - constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, 1 /* Source */, /*reportErrors*/ false)) { - reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString); - } - else { - reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString); - } + traceUnionsOrIntersectionsTooLarge(source, target); + var skipCaching = source.flags & 1048576 /* Union */ && source.types.length < 4 && !(target.flags & 1048576 /* Union */) || + target.flags & 1048576 /* Union */ && target.types.length < 4 && !(source.flags & 469499904 /* StructuredOrInstantiable */); + var result_7 = skipCaching ? + unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) : + recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags); + // For certain combinations involving intersections and optional, excess, or mismatched properties we need + // an extra property check where the intersection is viewed as a single object. The following are motivating + // examples that all should be errors, but aren't without this extra property check: + // + // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property + // + // declare let wrong: { a: { y: string } }; + // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type + // + // function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) { + // x = y; // Mismatched property in source intersection + // } + // + // We suppress recursive intersection property checks because they can generate lots of work when relating + // recursive intersections that are structurally similar but not exactly identical. See #37854. + if (result_7 && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || + isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { + inPropertyCheck = true; + result_7 &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags); + inPropertyCheck = false; + } + if (result_7) { + return result_7; } - return 0 /* False */; - } - traceUnionsOrIntersectionsTooLarge(source, target); - var result = 0 /* False */; - var saveErrorInfo = captureErrorCalculationState(); - if ((source.flags & 1048576 /* Union */ || target.flags & 1048576 /* Union */) && getConstituentCount(source) * getConstituentCount(target) < 4) { - // We skip caching when source or target is a union with no more than three constituents. - result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */); } - else if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) { - result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */, recursionFlags); + if (reportErrors) { + reportErrorResults(originalSource, originalTarget, source, target, headMessage); } - if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) { - if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState, recursionFlags)) { - resetErrorInfo(saveErrorInfo); + return 0 /* False */; + } + function reportErrorResults(originalSource, originalTarget, source, target, headMessage) { + var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); + var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); + source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; + target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; + var maybeSuppress = overrideNextErrorInfo > 0; + if (maybeSuppress) { + overrideNextErrorInfo--; + } + if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { + var currentError = errorInfo; + tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ true); + if (errorInfo !== currentError) { + maybeSuppress = !!errorInfo; + } + } + if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { + tryElaborateErrorsForPrimitivesAndObjects(source, target); + } + else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { + reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); + } + else if (ts.getObjectFlags(source) & 2048 /* JsxAttributes */ && target.flags & 2097152 /* Intersection */) { + var targetTypes = target.types; + var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); + var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); + if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && + (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { + // do not report top error + return; } } - if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) { - // The combined constraint of an intersection type is the intersection of the constraints of - // the constituents. When an intersection type contains instantiable types with union type - // constraints, there are situations where we need to examine the combined constraint. One is - // when the target is a union type. Another is when the intersection contains types belonging - // to one of the disjoint domains. For example, given type variables T and U, each with the - // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and - // we need to check this constraint against a union on the target side. Also, given a type - // variable V constrained to 'string | number', 'V & number' has a combined constraint of - // 'string & number | number & number' which reduces to just 'number'. - // This also handles type parameters, as a type parameter with a union constraint compared against a union - // needs to have its constraint hoisted into an intersection with said type parameter, this way - // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) - // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` - var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */)); - if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) { - if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself - // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this - if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { - resetErrorInfo(saveErrorInfo); - } - } - } + else { + errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); } - // For certain combinations involving intersections and optional, excess, or mismatched properties we need - // an extra property check where the intersection is viewed as a single object. The following are motivating - // examples that all should be errors, but aren't without this extra property check: - // - // let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 }; // Nested excess property - // - // declare let wrong: { a: { y: string } }; - // let weak: { a?: { x?: number } } & { c?: string } = wrong; // Nested weak object type - // - // function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) { - // x = y; // Mismatched property in source intersection - // } - // - // We suppress recursive intersection property checks because they can generate lots of work when relating - // recursive intersections that are structurally similar but not exactly identical. See #37854. - if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) || - isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 524288 /* NonInferrableType */); }))) { - inPropertyCheck = true; - result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */, recursionFlags); - inPropertyCheck = false; - } - reportErrorResults(source, target, result, isComparingJsxAttributes); - return result; - function reportErrorResults(source, target, result, isComparingJsxAttributes) { - if (!result && reportErrors) { - var sourceHasBase = !!getSingleBaseForNonAugmentingSubtype(originalSource); - var targetHasBase = !!getSingleBaseForNonAugmentingSubtype(originalTarget); - source = (originalSource.aliasSymbol || sourceHasBase) ? originalSource : source; - target = (originalTarget.aliasSymbol || targetHasBase) ? originalTarget : target; - var maybeSuppress = overrideNextErrorInfo > 0; - if (maybeSuppress) { - overrideNextErrorInfo--; - } - if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { - var currentError = errorInfo; - tryElaborateArrayLikeErrors(source, target, reportErrors); - if (errorInfo !== currentError) { - maybeSuppress = !!errorInfo; - } - } - if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) { - tryElaborateErrorsForPrimitivesAndObjects(source, target); - } - else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) { - reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead); - } - else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) { - var targetTypes = target.types; - var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode); - var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode); - if (!isErrorType(intrinsicAttributes) && !isErrorType(intrinsicClassAttributes) && - (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) { - // do not report top error - return result; - } - } - else { - errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); - } - if (!headMessage && maybeSuppress) { - lastSkippedInfo = [source, target]; - // Used by, eg, missing property checking to replace the top-level message with a more informative one - return result; - } - reportRelationError(headMessage, source, target); - } + if (!headMessage && maybeSuppress) { + lastSkippedInfo = [source, target]; + // Used by, eg, missing property checking to replace the top-level message with a more informative one + return; } + reportRelationError(headMessage, source, target); } function traceUnionsOrIntersectionsTooLarge(source, target) { if (!ts.tracing) { @@ -63507,21 +63912,6 @@ var ts; } } } - function isIdenticalTo(source, target, recursionFlags) { - if (source.flags !== target.flags) - return 0 /* False */; - if (source.flags & 67358815 /* Singleton */) - return -1 /* True */; - traceUnionsOrIntersectionsTooLarge(source, target); - if (source.flags & 3145728 /* UnionOrIntersection */) { - var result_7 = eachTypeRelatedToSomeType(source, target); - if (result_7) { - result_7 &= eachTypeRelatedToSomeType(target, source); - } - return result_7; - } - return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */, recursionFlags); - } function getTypeOfPropertyInTypes(types, name) { var appendPropType = function (propTypes, type) { var _a; @@ -63620,6 +64010,41 @@ var ts; function shouldCheckAsExcessProperty(prop, container) { return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration; } + function unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState) { + // Note that these checks are specifically ordered to produce correct results. In particular, + // we need to deconstruct unions before intersections (because unions are always at the top), + // and we need to handle "each" relations before "some" relations for the same kind of type. + if (source.flags & 1048576 /* Union */) { + return relation === comparableRelation ? + someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) : + eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState); + } + if (target.flags & 1048576 /* Union */) { + return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); + } + if (target.flags & 2097152 /* Intersection */) { + return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); + } + // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the + // constraints of all non-primitive types in the source into a new intersection. We do this because the + // intersection may further constrain the constraints of the non-primitive types. For example, given a type + // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't + // appear to be comparable to '2'. + if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { + var constraints = ts.sameMap(source.types, getBaseConstraintOrType); + if (constraints !== source.types) { + source = getIntersectionType(constraints); + if (!(source.flags & 2097152 /* Intersection */)) { + return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false); + } + } + } + // Check to see if any constituents of the intersection are immediately related to the target. + // Don't report errors though. Elaborating on whether a source constituent is related to the target is + // not actually useful and leads to some confusing error messages. Instead, we rely on the caller + // checking whether the full intersection viewed as an object is related to the target. + return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); + } function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; @@ -63655,8 +64080,11 @@ var ts; } } if (reportErrors) { + // Elaborate only if we can find a best matching type in the target union var bestMatchingType = getBestMatchingType(source, target, isRelatedTo); - isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], 2 /* Target */, /*reportErrors*/ true); + if (bestMatchingType) { + isRelatedTo(source, bestMatchingType, 2 /* Target */, /*reportErrors*/ true); + } } return 0 /* False */; } @@ -63792,7 +64220,8 @@ var ts; if (overflow) { return 0 /* False */; } - var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0), relation); + var keyIntersectionState = intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0); + var id = getRelationKey(source, target, keyIntersectionState, relation, /*ingnoreConstraints*/ false); var entry = relation.get(id); if (entry !== undefined) { if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) { @@ -63819,16 +64248,13 @@ var ts; targetStack = []; } else { - // generate a key where all type parameter id positions are replaced with unconstrained type parameter ids - // this isn't perfect - nested type references passed as type arguments will muck up the indexes and thus - // prevent finding matches- but it should hit up the common cases - var broadestEquivalentId = id.split(",").map(function (i) { return i.replace(/-\d+/g, function (_match, offset) { - var index = ts.length(id.slice(0, offset).match(/[-=]/g) || undefined); - return "=".concat(index); - }); }).join(","); + // A key that starts with "*" is an indication that we have type references that reference constrained + // type parameters. For such keys we also check against the key we would have gotten if all type parameters + // were unconstrained. + var broadestEquivalentId = id.startsWith("*") ? getRelationKey(source, target, keyIntersectionState, relation, /*ignoreConstraints*/ true) : undefined; for (var i = 0; i < maybeCount; i++) { // If source and target are already being compared, consider them related with assumptions - if (id === maybeKeys[i] || broadestEquivalentId === maybeKeys[i]) { + if (id === maybeKeys[i] || broadestEquivalentId && broadestEquivalentId === maybeKeys[i]) { return 3 /* Maybe */; } } @@ -63862,6 +64288,7 @@ var ts; return originalHandler(onlyUnreliable); }; } + var result; if (expandingFlags === 3 /* Both */) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", { sourceId: source.id, @@ -63871,8 +64298,13 @@ var ts; depth: sourceDepth, targetDepth: targetDepth }); + result = 3 /* Maybe */; + } + else { + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); + result = structuredTypeRelatedTo(source, target, reportErrors, intersectionState); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } - var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */; if (outofbandVarianceMarkerHandler) { outofbandVarianceMarkerHandler = originalHandler; } @@ -63904,98 +64336,97 @@ var ts; return result; } function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id }); - var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState); - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); - return result; - } - function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) { if (intersectionState & 4 /* PropertyCheck */) { return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */); } - if (intersectionState & 8 /* UnionIntersectionCheck */) { - // Note that these checks are specifically ordered to produce correct results. In particular, - // we need to deconstruct unions before intersections (because unions are always at the top), - // and we need to handle "each" relations before "some" relations for the same kind of type. - if (source.flags & 1048576 /* Union */) { - return relation === comparableRelation ? - someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) : - eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */); - } - if (target.flags & 1048576 /* Union */) { - return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */)); - } - if (target.flags & 2097152 /* Intersection */) { - return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */); - } - // Source is an intersection. For the comparable relation, if the target is a primitive type we hoist the - // constraints of all non-primitive types in the source into a new intersection. We do this because the - // intersection may further constrain the constraints of the non-primitive types. For example, given a type - // parameter 'T extends 1 | 2', the intersection 'T & 1' should be reduced to '1' such that it doesn't - // appear to be comparable to '2'. - if (relation === comparableRelation && target.flags & 131068 /* Primitive */) { - var constraints = ts.sameMap(source.types, getBaseConstraintOrType); - if (constraints !== source.types) { - source = getIntersectionType(constraints); - if (!(source.flags & 2097152 /* Intersection */)) { - return isRelatedTo(source, target, 1 /* Source */, /*reportErrors*/ false); - } + var result; + var originalErrorInfo; + var varianceCheckFailed = false; + var saveErrorInfo = captureErrorCalculationState(); + var sourceFlags = source.flags; + var targetFlags = target.flags; + if (relation === identityRelation) { + // We've already checked that source.flags and target.flags are identical + if (sourceFlags & 3145728 /* UnionOrIntersection */) { + var result_8 = eachTypeRelatedToSomeType(source, target); + if (result_8) { + result_8 &= eachTypeRelatedToSomeType(target, source); } + return result_8; } - // Check to see if any constituents of the intersection are immediately related to the target. - // - // Don't report errors though. Checking whether a constituent is related to the source is not actually - // useful and leads to some confusing error messages. Instead it is better to let the below checks - // take care of this, or to not elaborate at all. For instance, - // - // - For an object type (such as 'C = A & B'), users are usually more interested in structural errors. - // - // - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection - // than to report that 'D' is not assignable to 'A' or 'B'. - // - // - For a primitive type or type parameter (such as 'number = A & B') there is no point in - // breaking the intersection apart. - return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */); - } - var flags = source.flags & target.flags; - if (relation === identityRelation && !(flags & 524288 /* Object */)) { - if (flags & 4194304 /* Index */) { + if (sourceFlags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, 3 /* Both */, /*reportErrors*/ false); } - var result_8 = 0 /* False */; - if (flags & 8388608 /* IndexedAccess */) { - if (result_8 = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) { - return result_8; + if (sourceFlags & 8388608 /* IndexedAccess */) { + if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.indexType, target.indexType, 3 /* Both */, /*reportErrors*/ false)) { + return result; } } } - if (flags & 16777216 /* Conditional */) { + if (sourceFlags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_8 = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { - if (result_8 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { - return result_8; + if (result = isRelatedTo(source.checkType, target.checkType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(source.extendsType, target.extendsType, 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { + if (result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), 3 /* Both */, /*reportErrors*/ false)) { + return result; } } } } } } - if (flags & 33554432 /* Substitution */) { + if (sourceFlags & 33554432 /* Substitution */) { return isRelatedTo(source.substitute, target.substitute, 3 /* Both */, /*reportErrors*/ false); } - return 0 /* False */; + if (!(sourceFlags & 524288 /* Object */)) { + return 0 /* False */; + } + } + else if (sourceFlags & 3145728 /* UnionOrIntersection */ || targetFlags & 3145728 /* UnionOrIntersection */) { + if (result = unionOrIntersectionRelatedTo(source, target, reportErrors, intersectionState)) { + return result; + } + if (source.flags & 2097152 /* Intersection */ || source.flags & 262144 /* TypeParameter */ && target.flags & 1048576 /* Union */) { + // The combined constraint of an intersection type is the intersection of the constraints of + // the constituents. When an intersection type contains instantiable types with union type + // constraints, there are situations where we need to examine the combined constraint. One is + // when the target is a union type. Another is when the intersection contains types belonging + // to one of the disjoint domains. For example, given type variables T and U, each with the + // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and + // we need to check this constraint against a union on the target side. Also, given a type + // variable V constrained to 'string | number', 'V & number' has a combined constraint of + // 'string & number | number & number' which reduces to just 'number'. + // This also handles type parameters, as a type parameter with a union constraint compared against a union + // needs to have its constraint hoisted into an intersection with said type parameter, this way + // the type param can be compared with itself in the target (with the influence of its constraint to match other parts) + // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)` + var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */)); + if (constraint && everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself + // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this + if (result = isRelatedTo(constraint, target, 1 /* Source */, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } + // The ordered decomposition above doesn't handle all cases. Specifically, we also need to handle: + // Source is instantiable (e.g. source has union or intersection constraint). + // Source is an object, target is a union (e.g. { a, b: boolean } <=> { a, b: true } | { a, b: false }). + // Source is an intersection, target is an object (e.g. { a } & { b } <=> { a, b }). + // Source is an intersection, target is a union (e.g. { a } & { b: boolean } <=> { a, b: true } | { a, b: false }). + // Source is an intersection, target instantiable (e.g. string & { tag } <=> T["a"] constrained to string & { tag }). + if (!(sourceFlags & 465829888 /* Instantiable */ || + sourceFlags & 524288 /* Object */ && targetFlags & 1048576 /* Union */ || + sourceFlags & 2097152 /* Intersection */ && targetFlags & (524288 /* Object */ | 1048576 /* Union */ | 465829888 /* Instantiable */))) { + return 0 /* False */; + } } - var result; - var originalErrorInfo; - var varianceCheckFailed = false; - var saveErrorInfo = captureErrorCalculationState(); // We limit alias variance probing to only object and conditional types since their alias behavior // is more predictable than other, interned types, which may or may not have an alias depending on // the order in which things were checked. - if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && + if (sourceFlags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); @@ -64013,7 +64444,7 @@ var ts; isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0], 2 /* Target */))) { return result; } - if (target.flags & 262144 /* TypeParameter */) { + if (targetFlags & 262144 /* TypeParameter */) { // A source type { [P in Q]: X } is related to a target type T if keyof T is related to Q and X is related to T[Q]. if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source), 3 /* Both */)) { if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) { @@ -64025,10 +64456,10 @@ var ts; } } } - else if (target.flags & 4194304 /* Index */) { + else if (targetFlags & 4194304 /* Index */) { var targetType_1 = target.type; // A keyof S is related to a keyof T if T is related to S. - if (source.flags & 4194304 /* Index */) { + if (sourceFlags & 4194304 /* Index */) { if (result = isRelatedTo(targetType_1, source.type, 3 /* Both */, /*reportErrors*/ false)) { return result; } @@ -64079,8 +64510,8 @@ var ts; } } } - else if (target.flags & 8388608 /* IndexedAccess */) { - if (source.flags & 8388608 /* IndexedAccess */) { + else if (targetFlags & 8388608 /* IndexedAccess */) { + if (sourceFlags & 8388608 /* IndexedAccess */) { // Relate components directly before falling back to constraint relationships // A type S[K] is related to a type T[J] if S is related to T and K is related to J. if (result = isRelatedTo(source.objectType, target.objectType, 3 /* Both */, reportErrors)) { @@ -64186,7 +64617,7 @@ var ts; } } } - else if (target.flags & 16777216 /* Conditional */) { + else if (targetFlags & 16777216 /* Conditional */) { // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(target, targetStack, targetDepth, 10)) { @@ -64211,8 +64642,8 @@ var ts; } } } - else if (target.flags & 134217728 /* TemplateLiteral */) { - if (source.flags & 134217728 /* TemplateLiteral */) { + else if (targetFlags & 134217728 /* TemplateLiteral */) { + if (sourceFlags & 134217728 /* TemplateLiteral */) { if (relation === comparableRelation) { return templateLiteralTypesDefinitelyUnrelated(source, target) ? 0 /* False */ : -1 /* True */; } @@ -64224,11 +64655,11 @@ var ts; return -1 /* True */; } } - if (source.flags & 8650752 /* TypeVariable */) { - // IndexedAccess comparisons are handled above in the `target.flags & TypeFlage.IndexedAccess` branch - if (!(source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */)) { + if (sourceFlags & 8650752 /* TypeVariable */) { + // IndexedAccess comparisons are handled above in the `targetFlags & TypeFlage.IndexedAccess` branch + if (!(sourceFlags & 8388608 /* IndexedAccess */ && targetFlags & 8388608 /* IndexedAccess */)) { var constraint = getConstraintOfType(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { + if (!constraint || (sourceFlags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */), 3 /* Both */)) { resetErrorInfo(saveErrorInfo); @@ -64241,20 +64672,31 @@ var ts; return result; } // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example - else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(target.flags & source.flags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { + else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, 1 /* Source */, reportErrors && !(targetFlags & sourceFlags & 262144 /* TypeParameter */), /*headMessage*/ undefined, intersectionState)) { resetErrorInfo(saveErrorInfo); return result; } + if (isMappedTypeGenericIndexedAccess(source)) { + // For an indexed access type { [P in K]: E}[X], above we have already explored an instantiation of E with X + // substituted for P. We also want to explore type { [P in K]: E }[C], where C is the constraint of X. + var indexConstraint = getConstraintOfType(source.indexType); + if (indexConstraint) { + if (result = isRelatedTo(getIndexedAccessType(source.objectType, indexConstraint), target, 1 /* Source */, reportErrors)) { + resetErrorInfo(saveErrorInfo); + return result; + } + } + } } } - else if (source.flags & 4194304 /* Index */) { + else if (sourceFlags & 4194304 /* Index */) { if (result = isRelatedTo(keyofConstraintType, target, 1 /* Source */, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; } } - else if (source.flags & 134217728 /* TemplateLiteral */ && !(target.flags & 524288 /* Object */)) { - if (!(target.flags & 134217728 /* TemplateLiteral */)) { + else if (sourceFlags & 134217728 /* TemplateLiteral */ && !(targetFlags & 524288 /* Object */)) { + if (!(targetFlags & 134217728 /* TemplateLiteral */)) { var constraint = getBaseConstraintOfType(source); if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, 1 /* Source */, reportErrors))) { resetErrorInfo(saveErrorInfo); @@ -64262,8 +64704,8 @@ var ts; } } } - else if (source.flags & 268435456 /* StringMapping */) { - if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { + else if (sourceFlags & 268435456 /* StringMapping */) { + if (targetFlags & 268435456 /* StringMapping */ && source.symbol === target.symbol) { if (result = isRelatedTo(source.type, target.type, 3 /* Both */, reportErrors)) { resetErrorInfo(saveErrorInfo); return result; @@ -64277,14 +64719,14 @@ var ts; } } } - else if (source.flags & 16777216 /* Conditional */) { + else if (sourceFlags & 16777216 /* Conditional */) { // If we reach 10 levels of nesting for the same conditional type, assume it is an infinitely expanding recursive // conditional type and bail out with a Ternary.Maybe result. if (isDeeplyNestedType(source, sourceStack, sourceDepth, 10)) { resetErrorInfo(saveErrorInfo); return 3 /* Maybe */; } - if (target.flags & 16777216 /* Conditional */) { + if (targetFlags & 16777216 /* Conditional */) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, // and Y1 is related to Y2. @@ -64312,7 +64754,7 @@ var ts; else { // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way // more assignments than are desirable (since it maps the source check type to its constraint, it loses information) - var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); + var distributiveConstraint = hasNonCircularBaseConstraint(source) ? getConstraintOfDistributiveConditionalType(source) : undefined; if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, 1 /* Source */, reportErrors)) { resetErrorInfo(saveErrorInfo); @@ -64344,9 +64786,10 @@ var ts; } return 0 /* False */; } - var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); + var sourceIsPrimitive = !!(sourceFlags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); + sourceFlags = source.flags; } else if (isGenericMappedType(source)) { return 0 /* False */; @@ -64388,7 +64831,7 @@ var ts; // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. - if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) { + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 524288 /* Object */) { // Report structural errors only if we haven't reported any errors yet var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive; result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState); @@ -64412,7 +64855,7 @@ var ts; // there exists a constituent of T for every combination of the discriminants of S // with respect to T. We do not report errors here, as we will use the existing // error result from checking each constituent of the union. - if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) { + if (sourceFlags & (524288 /* Object */ | 2097152 /* Intersection */) && targetFlags & 1048576 /* Union */) { var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */); if (objectOnlyTarget.flags & 1048576 /* Union */) { var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget); @@ -64858,7 +65301,7 @@ var ts; for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) { var targetProp = _c[_b]; var name = targetProp.escapedName; - if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) { + if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || ts.isNumericLiteralName(name) || name === "length")) { var sourceProp = getPropertyOfType(source, name); if (sourceProp && sourceProp !== targetProp) { var related = propertyRelatedTo(source, target, sourceProp, targetProp, getNonMissingTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation); @@ -64927,11 +65370,11 @@ var ts; } } var result = -1 /* True */; - var saveErrorInfo = captureErrorCalculationState(); var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn; var sourceObjectFlags = ts.getObjectFlags(source); var targetObjectFlags = ts.getObjectFlags(target); - if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) { + if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol || + sourceObjectFlags & 4 /* Reference */ && targetObjectFlags & 4 /* Reference */ && source.target === target.target) { // We have instantiations of the same anonymous type (which typically will be the type of a // method). Simply do a pairwise comparison of the signatures in the two signature lists instead // of the much more expensive N * M comparison matrix we explore below. We erase type parameters @@ -64967,6 +65410,7 @@ var ts; else { outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { var t = targetSignatures_1[_i]; + var saveErrorInfo = captureErrorCalculationState(); // Only elaborate errors from the first failure var shouldElaborateErrors = reportErrors; for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) { @@ -65335,48 +65779,56 @@ var ts; function isTypeReferenceWithGenericArguments(type) { return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t); }); } - /** - * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1" - * where A.id=111 and number.id=12 - */ - function getTypeReferenceId(type, typeParameters, depth) { - if (depth === void 0) { depth = 0; } - var result = "" + type.target.id; - for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) { - var t = _a[_i]; - if (isUnconstrainedTypeParameter(t)) { - var index = typeParameters.indexOf(t); - if (index < 0) { - index = typeParameters.length; - typeParameters.push(t); + function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) { + var typeParameters = []; + var constraintMarker = ""; + var sourceId = getTypeReferenceId(source, 0); + var targetId = getTypeReferenceId(target, 0); + return "".concat(constraintMarker).concat(sourceId, ",").concat(targetId).concat(postFix); + // getTypeReferenceId(A<T, number, U>) returns "111=0-12=1" + // where A.id=111 and number.id=12 + function getTypeReferenceId(type, depth) { + if (depth === void 0) { depth = 0; } + var result = "" + type.target.id; + for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) { + var t = _a[_i]; + if (t.flags & 262144 /* TypeParameter */) { + if (ignoreConstraints || isUnconstrainedTypeParameter(t)) { + var index = typeParameters.indexOf(t); + if (index < 0) { + index = typeParameters.length; + typeParameters.push(t); + } + result += "=" + index; + continue; + } + // We mark type references that reference constrained type parameters such that we know to obtain + // and look for a "broadest equivalent key" in the cache. + constraintMarker = "*"; + } + else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { + result += "<" + getTypeReferenceId(t, depth + 1) + ">"; + continue; } - result += "=" + index; - } - else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) { - result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">"; - } - else { result += "-" + t.id; } + return result; } - return result; } /** * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters. * For other cases, the types ids are used. */ - function getRelationKey(source, target, intersectionState, relation) { + function getRelationKey(source, target, intersectionState, relation, ignoreConstraints) { if (relation === identityRelation && source.id > target.id) { var temp = source; source = target; target = temp; } var postFix = intersectionState ? ":" + intersectionState : ""; - if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) { - var typeParameters = []; - return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix; - } - return source.id + "," + target.id + postFix; + return isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target) ? + getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) : + "".concat(source.id, ",").concat(target.id).concat(postFix); } // Invoke the callback for each underlying property symbol of the given symbol and return the first // value that isn't undefined. @@ -65424,28 +65876,35 @@ var ts; !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; } // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons - // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, + // for maxDepth or more occurrences or instantiations of the type have been recorded on the given stack. It is possible, // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely - // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5 + // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least maxDepth // levels, but unequal at some level beyond that. - // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially - // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives - // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). - // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of + // In addition, this will also detect when an indexed access has been chained off of maxDepth more times (which is + // essentially the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding + // false positives for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`). + // It also detects when a recursive type reference has expanded maxDepth or more times, e.g. if the true branch of // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]` - // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]` - // in such cases we need to terminate the expansion, and we do so here. + // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`. In such cases we need + // to terminate the expansion, and we do so here. function isDeeplyNestedType(type, stack, depth, maxDepth) { - if (maxDepth === void 0) { maxDepth = 5; } + if (maxDepth === void 0) { maxDepth = 3; } if (depth >= maxDepth) { var identity_1 = getRecursionIdentity(type); var count = 0; + var lastTypeId = 0; for (var i = 0; i < depth; i++) { - if (getRecursionIdentity(stack[i]) === identity_1) { - count++; - if (count >= maxDepth) { - return true; + var t = stack[i]; + if (getRecursionIdentity(t) === identity_1) { + // We only count occurrences with a higher type id than the previous occurrence, since higher + // type ids are an indicator of newer instantiations caused by recursion. + if (t.id >= lastTypeId) { + count++; + if (count >= maxDepth) { + return true; + } } + lastTypeId = t.id; } } } @@ -65740,7 +66199,7 @@ var ts; } function getBaseTypeOfLiteralType(type) { return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) : - type.flags & 128 /* StringLiteral */ ? stringType : + type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : @@ -65951,9 +66410,12 @@ var ts; * with no call or construct signatures. */ function isObjectTypeWithInferableIndex(type) { - return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) : - !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && - !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); + return type.flags & 2097152 /* Intersection */ + ? ts.every(type.types, isObjectTypeWithInferableIndex) + : !!(type.symbol + && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 + && !(type.symbol.flags & 32 /* Class */) + && !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source)); } function createSymbolWithType(source, type) { var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */); @@ -66753,12 +67215,14 @@ var ts; // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType || - (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { + if (source === nonInferrableAnyType || source === silentNeverType || (priority & 128 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) { return; } var inference = getInferenceInfoForType(target); if (inference) { + if (ts.getObjectFlags(source) & 524288 /* NonInferrableType */) { + return; + } if (!inference.isFixed) { if (inference.priority === undefined || priority < inference.priority) { inference.candidates = undefined; @@ -66789,21 +67253,19 @@ var ts; inferencePriority = Math.min(inferencePriority, priority); return; } - else { - // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine - var simplified = getSimplifiedType(target, /*writing*/ false); - if (simplified !== target) { - invokeOnce(source, simplified, inferFromTypes); - } - else if (target.flags & 8388608 /* IndexedAccess */) { - var indexType = getSimplifiedType(target.indexType, /*writing*/ false); - // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider - // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. - if (indexType.flags & 465829888 /* Instantiable */) { - var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false); - if (simplified_1 && simplified_1 !== target) { - invokeOnce(source, simplified_1, inferFromTypes); - } + // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine + var simplified = getSimplifiedType(target, /*writing*/ false); + if (simplified !== target) { + inferFromTypes(source, simplified); + } + else if (target.flags & 8388608 /* IndexedAccess */) { + var indexType = getSimplifiedType(target.indexType, /*writing*/ false); + // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider + // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can. + if (indexType.flags & 465829888 /* Instantiable */) { + var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false); + if (simplified_1 && simplified_1 !== target) { + inferFromTypes(source, simplified_1); } } } @@ -67455,6 +67917,11 @@ var ts; case "BigInt64Array": case "BigUint64Array": return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later; + case "await": + if (ts.isCallExpression(node.parent)) { + return ts.Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; + } + // falls through default: if (node.parent.kind === 295 /* ShorthandPropertyAssignment */) { return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; @@ -67551,35 +68018,13 @@ var ts; } return false; } - function getPropertyAccess(expr) { - if (ts.isAccessExpression(expr)) { - return expr; - } - if (ts.isIdentifier(expr)) { - var symbol = getResolvedSymbol(expr); - if (isConstVariable(symbol)) { - var declaration = symbol.valueDeclaration; - // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' - if (ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && ts.isAccessExpression(declaration.initializer)) { - return declaration.initializer; - } - // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' - if (ts.isBindingElement(declaration) && !declaration.initializer) { - var parent = declaration.parent.parent; - if (ts.isVariableDeclaration(parent) && !parent.type && parent.initializer && (ts.isIdentifier(parent.initializer) || ts.isAccessExpression(parent.initializer))) { - return declaration; - } - } - } - } - return undefined; - } function getAccessedPropertyName(access) { var propertyName; return access.kind === 205 /* PropertyAccessExpression */ ? access.name.escapedText : access.kind === 206 /* ElementAccessExpression */ && ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : access.kind === 202 /* BindingElement */ && (propertyName = getDestructuringPropertyName(access)) ? ts.escapeLeadingUnderscores(propertyName) : - undefined; + access.kind === 163 /* Parameter */ ? ("" + access.parent.parameters.indexOf(access)) : + undefined; } function containsMatchingReference(source, target) { while (ts.isAccessExpression(source)) { @@ -67812,7 +68257,10 @@ var ts; (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */; } - if (flags & 524288 /* Object */ && !ignoreObjects) { + if (flags & 524288 /* Object */) { + if (ignoreObjects) { + return 16768959 /* AndFactsMask */; // This is the identity element for computing type facts of intersection. + } return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? @@ -67845,10 +68293,23 @@ var ts; // When an intersection contains a primitive type we ignore object type constituents as they are // presumably type tags. For example, in string & { __kind__: "name" } we ignore the object type. ignoreObjects || (ignoreObjects = maybeTypeOfKind(type, 131068 /* Primitive */)); - return ts.reduceLeft(type.types, function (facts, t) { return facts & getTypeFacts(t, ignoreObjects); }, 16777215 /* All */); + return getIntersectionTypeFacts(type, ignoreObjects); } return 16777215 /* All */; } + function getIntersectionTypeFacts(type, ignoreObjects) { + // When computing the type facts of an intersection type, certain type facts are computed as `and` + // and others are computed as `or`. + var oredFacts = 0 /* None */; + var andedFacts = 16777215 /* All */; + for (var _i = 0, _a = type.types; _i < _a.length; _i++) { + var t = _a[_i]; + var f = getTypeFacts(t, ignoreObjects); + oredFacts |= f; + andedFacts &= f; + } + return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 16768959 /* AndFactsMask */; + } function getTypeWithFacts(type, include) { return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } @@ -68120,9 +68581,6 @@ var ts; getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : mapType(type, mapper); } - function getConstituentCount(type) { - return type.flags & 1048576 /* Union */ ? type.types.length : 1; - } function extractTypesOfKind(type, kind) { return filterType(type, function (t) { return (t.flags & kind) !== 0; }); } @@ -68472,20 +68930,21 @@ var ts; } return false; } - function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer) { + function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, flowNode) { if (initialType === void 0) { initialType = declaredType; } + if (flowNode === void 0) { flowNode = reference.flowNode; } var key; var isKeySet = false; var flowDepth = 0; if (flowAnalysisDisabled) { return errorType; } - if (!reference.flowNode) { + if (!flowNode) { return declaredType; } flowInvocationCount++; var sharedFlowStart = sharedFlowCount; - var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode)); sharedFlowCount = sharedFlowStart; // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations @@ -68917,13 +69376,58 @@ var ts; } return result; } + function getCandidateDiscriminantPropertyAccess(expr) { + if (ts.isBindingPattern(reference) || ts.isFunctionExpressionOrArrowFunction(reference)) { + // When the reference is a binding pattern or function or arrow expression, we are narrowing a pesudo-reference in + // getNarrowedTypeOfSymbol. An identifier for a destructuring variable declared in the same binding pattern or + // parameter declared in the same parameter list is a candidate. + if (ts.isIdentifier(expr)) { + var symbol = getResolvedSymbol(expr); + var declaration = symbol.valueDeclaration; + if (declaration && (ts.isBindingElement(declaration) || ts.isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) { + return declaration; + } + } + } + else if (ts.isAccessExpression(expr)) { + // An access expression is a candidate if the reference matches the left hand expression. + if (isMatchingReference(reference, expr.expression)) { + return expr; + } + } + else if (ts.isIdentifier(expr)) { + var symbol = getResolvedSymbol(expr); + if (isConstVariable(symbol)) { + var declaration = symbol.valueDeclaration; + // Given 'const x = obj.kind', allow 'x' as an alias for 'obj.kind' + if (ts.isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && ts.isAccessExpression(declaration.initializer) && + isMatchingReference(reference, declaration.initializer.expression)) { + return declaration.initializer; + } + // Given 'const { kind: x } = obj', allow 'x' as an alias for 'obj.kind' + if (ts.isBindingElement(declaration) && !declaration.initializer) { + var parent = declaration.parent.parent; + if (ts.isVariableDeclaration(parent) && !parent.type && parent.initializer && (ts.isIdentifier(parent.initializer) || ts.isAccessExpression(parent.initializer)) && + isMatchingReference(reference, parent.initializer)) { + return declaration; + } + } + } + } + return undefined; + } function getDiscriminantPropertyAccess(expr, computedType) { - var access, name; var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType; - return type.flags & 1048576 /* Union */ && (access = getPropertyAccess(expr)) && (name = getAccessedPropertyName(access)) && - isMatchingReference(reference, ts.isAccessExpression(access) ? access.expression : access.parent.parent.initializer) && - isDiscriminantProperty(type, name) ? - access : undefined; + if (type.flags & 1048576 /* Union */) { + var access = getCandidateDiscriminantPropertyAccess(expr); + if (access) { + var name = getAccessedPropertyName(access); + if (name && isDiscriminantProperty(type, name)) { + return access; + } + } + } + return undefined; } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); @@ -68990,7 +69494,7 @@ var ts; function narrowByInKeyword(type, name, assumeTrue) { if (type.flags & 1048576 /* Union */ || type.flags & 524288 /* Object */ && declaredType !== type - || isThisTypeParameter(type) + || ts.isThisTypeParameter(type) || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) { return filterType(type, function (t) { return isTypePresencePossible(t, name, assumeTrue); }); } @@ -69627,12 +70131,16 @@ var ts; function isGenericTypeWithoutNullableConstraint(type) { return !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */)); } - function hasNonBindingPatternContextualTypeWithNoGenericTypes(node) { + function hasContextualTypeWithNoGenericTypes(node, checkMode) { // Computing the contextual type for a child of a JSX element involves resolving the type of the // element's tag name, so we exclude that here to avoid circularities. + // If check mode has `CheckMode.RestBindingElement`, we skip binding pattern contextual types, + // as we want the type of a rest element to be generic when possible. var contextualType = (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !((ts.isJsxOpeningElement(node.parent) || ts.isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && - getContextualType(node, 8 /* SkipBindingPatterns */); + (checkMode && checkMode & 32 /* RestBindingElement */ ? + getContextualType(node, 8 /* SkipBindingPatterns */) + : getContextualType(node)); return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { @@ -69645,7 +70153,7 @@ var ts; // 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'. var substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && - (isConstraintPosition(type, reference) || hasNonBindingPatternContextualTypeWithNoGenericTypes(reference)); + (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); return substituteConstraints ? mapType(type, function (t) { return t.flags & 465829888 /* Instantiable */ ? getBaseConstraintOrType(t) : t; }) : type; } function isExportOrExportExpression(location) { @@ -69681,7 +70189,92 @@ var ts; } } } + function getNarrowedTypeOfSymbol(symbol, location) { + var declaration = symbol.valueDeclaration; + if (declaration) { + // If we have a non-rest binding element with no initializer declared as a const variable or a const-like + // parameter (a parameter for which there are no assignments in the function body), and if the parent type + // for the destructuring is a union type, one or more of the binding elements may represent discriminant + // properties, and we want the effects of conditional checks on such discriminants to affect the types of + // other binding elements from the same destructuring. Consider: + // + // type Action = + // | { kind: 'A', payload: number } + // | { kind: 'B', payload: string }; + // + // function f({ kind, payload }: Action) { + // if (kind === 'A') { + // payload.toFixed(); + // } + // if (kind === 'B') { + // payload.toUpperCase(); + // } + // } + // + // Above, we want the conditional checks on 'kind' to affect the type of 'payload'. To facilitate this, we use + // the binding pattern AST instance for '{ kind, payload }' as a pseudo-reference and narrow this reference + // as if it occurred in the specified location. We then recompute the narrowed binding element type by + // destructuring from the narrowed parent type. + if (ts.isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) { + var parent = declaration.parent.parent; + if (parent.kind === 253 /* VariableDeclaration */ && ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || parent.kind === 163 /* Parameter */) { + var links = getNodeLinks(location); + if (!(links.flags & 268435456 /* InCheckIdentifier */)) { + links.flags |= 268435456 /* InCheckIdentifier */; + var parentType = getTypeForBindingElementParent(parent, 0 /* Normal */); + links.flags &= ~268435456 /* InCheckIdentifier */; + if (parentType && parentType.flags & 1048576 /* Union */ && !(parent.kind === 163 /* Parameter */ && isSymbolAssigned(symbol))) { + var pattern = declaration.parent; + var narrowedType = getFlowTypeOfReference(pattern, parentType, parentType, /*flowContainer*/ undefined, location.flowNode); + if (narrowedType.flags & 131072 /* Never */) { + return neverType; + } + return getBindingElementTypeFromParentType(declaration, narrowedType); + } + } + } + } + // If we have a const-like parameter with no type annotation or initializer, and if the parameter is contextually + // typed by a signature with a single rest parameter of a union of tuple types, one or more of the parameters may + // represent discriminant tuple elements, and we want the effects of conditional checks on such discriminants to + // affect the types of other parameters in the same parameter list. Consider: + // + // type Action = [kind: 'A', payload: number] | [kind: 'B', payload: string]; + // + // const f: (...args: Action) => void = (kind, payload) => { + // if (kind === 'A') { + // payload.toFixed(); + // } + // if (kind === 'B') { + // payload.toUpperCase(); + // } + // } + // + // Above, we want the conditional checks on 'kind' to affect the type of 'payload'. To facilitate this, we use + // the arrow function AST node for '(kind, payload) => ...' as a pseudo-reference and narrow this reference as + // if it occurred in the specified location. We then recompute the narrowed parameter type by indexing into the + // narrowed tuple type. + if (ts.isParameter(declaration) && !declaration.type && !declaration.initializer && !declaration.dotDotDotToken) { + var func = declaration.parent; + if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) { + var contextualSignature = getContextualSignature(func); + if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) { + var restType = getTypeOfSymbol(contextualSignature.parameters[0]); + if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !isSymbolAssigned(symbol)) { + var narrowedType = getFlowTypeOfReference(func, restType, restType, /*flowContainer*/ undefined, location.flowNode); + var index = func.parameters.indexOf(declaration) - (ts.getThisParameter(func) ? 1 : 0); + return getIndexedAccessType(narrowedType, getNumberLiteralType(index)); + } + } + } + } + } + return getTypeOfSymbol(symbol); + } function checkIdentifier(node, checkMode) { + if (ts.isThisInTypeQuery(node)) { + return checkThisExpression(node); + } var symbol = getResolvedSymbol(node); if (symbol === unknownSymbol) { return errorType; @@ -69715,9 +70308,9 @@ var ts; markAliasReferenced(symbol, node); } var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol; - if (sourceSymbol.declarations && getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) { - addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText); + var targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } var declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { @@ -69754,7 +70347,7 @@ var ts; } } checkNestedBlockScopedBinding(node, symbol); - var type = getTypeOfSymbol(localOrExportSymbol); + var type = getNarrowedTypeOfSymbol(localOrExportSymbol, node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */) && @@ -70484,7 +71077,7 @@ var ts; var parent = declaration.parent.parent; var name = declaration.propertyName || declaration.name; var parentType = getContextualTypeForVariableLikeDeclaration(parent) || - parent.kind !== 202 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent); + parent.kind !== 202 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name)) return undefined; if (parent.name.kind === 201 /* ArrayBindingPattern */) { @@ -70797,13 +71390,13 @@ var ts; function isCircularMappedProperty(symbol) { return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0); } - function getTypeOfPropertyOfContextualType(type, name) { + function getTypeOfPropertyOfContextualType(type, name, nameType) { return mapType(type, function (t) { var _a; if (isGenericMappedType(t)) { var constraint = getConstraintTypeFromMappedType(t); var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; - var propertyNameType = getStringLiteralType(ts.unescapeLeadingUnderscores(name)); + var propertyNameType = nameType || getStringLiteralType(ts.unescapeLeadingUnderscores(name)); if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { return substituteIndexedMappedType(t, propertyNameType); } @@ -70815,11 +71408,11 @@ var ts; } if (isTupleType(t)) { var restType = getRestTypeOfTupleType(t); - if (restType && isNumericLiteralName(name) && +name >= 0) { + if (restType && ts.isNumericLiteralName(name) && +name >= 0) { return restType; } } - return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), getStringLiteralType(ts.unescapeLeadingUnderscores(name)))) === null || _a === void 0 ? void 0 : _a.type; + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(ts.unescapeLeadingUnderscores(name)))) === null || _a === void 0 ? void 0 : _a.type; } return undefined; }, /*noReductions*/ true); @@ -70847,7 +71440,8 @@ var ts; // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - return getTypeOfPropertyOfContextualType(type, getSymbolOfNode(element).escapedName); + var symbol = getSymbolOfNode(element); + return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType); } if (element.name) { var nameType_2 = getLiteralTypeFromPropertyName(element.name); @@ -71455,10 +72049,10 @@ var ts; case 161 /* ComputedPropertyName */: return isNumericComputedName(name); case 79 /* Identifier */: - return isNumericLiteralName(name.escapedText); + return ts.isNumericLiteralName(name.escapedText); case 8 /* NumericLiteral */: case 10 /* StringLiteral */: - return isNumericLiteralName(name.text); + return ts.isNumericLiteralName(name.text); default: return false; } @@ -71468,35 +72062,12 @@ var ts; // but this behavior is consistent with checkIndexedAccess return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */); } - function isNumericLiteralName(name) { - // The intent of numeric names is that - // - they are names with text in a numeric form, and that - // - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit', - // acquired by applying the abstract 'ToNumber' operation on the name's text. - // - // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name. - // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold. - // - // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)' - // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'. - // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names - // because their 'ToString' representation is not equal to their original text. - // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1. - // - // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'. - // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation. - // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number. - // - // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional. - // This is desired behavior, because when indexing with them as numeric entities, you are indexing - // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively. - return (+name).toString() === name; - } function checkComputedPropertyName(node) { var links = getNodeLinks(node.expression); if (!links.resolvedType) { if ((ts.isTypeLiteralNode(node.parent.parent) || ts.isClassLike(node.parent.parent) || ts.isInterfaceDeclaration(node.parent.parent)) - && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */) { + && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 101 /* InKeyword */ + && node.parent.kind !== 171 /* GetAccessor */ && node.parent.kind !== 172 /* SetAccessor */) { return links.resolvedType = errorType; } links.resolvedType = checkExpression(node.expression); @@ -71527,7 +72098,7 @@ var ts; function isSymbolWithNumericName(symbol) { var _a; var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0]; - return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name)); + return ts.isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name)); } function isSymbolWithSymbolName(symbol) { var _a; @@ -71766,15 +72337,9 @@ var ts; } } function isValidSpreadType(type) { - if (type.flags & 465829888 /* Instantiable */) { - var constraint = getBaseConstraintOfType(type); - if (constraint !== undefined) { - return isValidSpreadType(constraint); - } - } - return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || - getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) || - type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType)); + var t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType)); + return !!(t.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || + t.flags & 3145728 /* UnionOrIntersection */ && ts.every(t.types, isValidSpreadType)); } function checkJsxSelfClosingElementDeferred(node) { checkJsxOpeningLikeElementOrOpeningFragment(node); @@ -72579,11 +73144,14 @@ var ts; if (!ts.getContainingClass(privId)) { return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } - if (!ts.isExpressionNode(privId)) { - return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression); - } - if (!getSymbolForPrivateIdentifierExpression(privId)) { - return grammarErrorOnNode(privId, ts.Diagnostics.Cannot_find_name_0, ts.idText(privId)); + if (!ts.isForInStatement(privId.parent)) { + if (!ts.isExpressionNode(privId)) { + return grammarErrorOnNode(privId, ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression); + } + var isInOperation = ts.isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 101 /* InKeyword */; + if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) { + return grammarErrorOnNode(privId, ts.Diagnostics.Cannot_find_name_0, ts.idText(privId)); + } } return false; } @@ -72668,23 +73236,6 @@ var ts; if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && ts.isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) { grammarErrorOnNode(right, ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, ts.idText(right)); } - if ((lexicallyScopedSymbol === null || lexicallyScopedSymbol === void 0 ? void 0 : lexicallyScopedSymbol.valueDeclaration) && (ts.getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && !useDefineForClassFields)) { - var lexicalClass_1 = ts.getContainingClass(lexicallyScopedSymbol.valueDeclaration); - var parentStaticFieldInitializer = ts.findAncestor(node, function (n) { - if (n === lexicalClass_1) - return "quit"; - if (ts.isPropertyDeclaration(n.parent) && ts.hasStaticModifier(n.parent) && n.parent.initializer === n && n.parent.parent === lexicalClass_1) { - return true; - } - return false; - }); - if (parentStaticFieldInitializer) { - var parentStaticFieldInitializerSymbol = getSymbolOfNode(parentStaticFieldInitializer.parent); - ts.Debug.assert(parentStaticFieldInitializerSymbol, "Initializer without declaration symbol"); - var diagnostic = error(node, ts.Diagnostics.Property_0_may_not_be_used_in_a_static_property_s_initializer_in_the_same_class_when_target_is_esnext_and_useDefineForClassFields_is_false, ts.symbolName(lexicallyScopedSymbol)); - ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(parentStaticFieldInitializer.parent, ts.Diagnostics.Initializer_for_property_0, ts.symbolName(parentStaticFieldInitializerSymbol))); - } - } if (isAnyLike) { if (lexicallyScopedSymbol) { return isErrorType(apparentType) ? errorType : apparentType; @@ -72725,7 +73276,7 @@ var ts; } var propType; if (!prop) { - var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? + var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || ts.isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : undefined; if (!(indexInfo && indexInfo.type)) { var isUncheckedJS = isUncheckedJSSuggestion(node, leftType.symbol, /*excludeClasses*/ true); @@ -72742,7 +73293,7 @@ var ts; return anyType; } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); + reportNonexistentProperty(right, ts.isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS); } return errorType; } @@ -72755,7 +73306,7 @@ var ts; } } else { - if (prop.declarations && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) { + if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { addDeprecatedSuggestion(right, prop.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); @@ -72767,7 +73318,7 @@ var ts; error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right)); return errorType; } - propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getSetAccessorTypeOfSymbol(prop) : getTypeOfSymbol(prop); + propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writing ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop); } return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode); } @@ -73035,7 +73586,7 @@ var ts; } function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) { ts.Debug.assert(outerName !== undefined, "outername should always be defined"); - var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) { + var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, /*getSpellingSuggestions*/ true, function (symbols, name, meaning) { ts.Debug.assertEqual(outerName, name, "name should equal outerName"); var symbol = getSymbol(symbols, name, meaning); // Sometimes the symbol is found when location is a return type of a function: `typeof x` and `x` is declared in the body of the function @@ -73281,7 +73832,7 @@ var ts; } var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType; var accessFlags = ts.isAssignmentTarget(node) ? - 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0) : + 4 /* Writing */ | (isGenericObjectType(objectType) && !ts.isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0) : 32 /* ExpressionPosition */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType; return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node); @@ -74214,7 +74765,7 @@ var ts; } var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics); ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures"); - var chain = ts.chainDiagnosticMessages(ts.map(diags_3, function (d) { return typeof d.messageText === "string" ? d : d.messageText; }), ts.Diagnostics.No_overload_matches_this_call); + var chain = ts.chainDiagnosticMessages(ts.map(diags_3, ts.createDiagnosticMessageChainFromDiagnostic), ts.Diagnostics.No_overload_matches_this_call); // The below is a spread to guarantee we get a new (mutable) array - our `flatMap` helper tries to do "smart" optimizations where it reuses input // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic var related = __spreadArray([], ts.flatMap(diags_3, function (d) { return d.relatedInformation; }), true); @@ -74431,7 +74982,7 @@ var ts; typeArguments.pop(); } while (typeArguments.length < typeParameters.length) { - typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); + typeArguments.push(getDefaultFromTypeParameter(typeParameters[typeArguments.length]) || getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs)); } return typeArguments; } @@ -75087,8 +75638,7 @@ var ts; */ function checkCallExpression(node, checkMode) { var _a; - if (!checkGrammarTypeArguments(node, node.typeArguments)) - checkGrammarArguments(node.arguments); + checkGrammarTypeArguments(node, node.typeArguments); var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode); if (signature === resolvingSignature) { // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that @@ -75193,8 +75743,7 @@ var ts; } function checkImportCallExpression(node) { // Check grammar of dynamic import - if (!checkGrammarArguments(node.arguments)) - checkGrammarImportCallExpression(node); + checkGrammarImportCallExpression(node); if (node.arguments.length === 0) { return createPromiseReturnType(node, anyType); } @@ -75239,8 +75788,8 @@ var ts; if (hasDefaultOnly && type && !isErrorType(type)) { var synthType = type; if (!synthType.defaultOnlyType) { - var type_4 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); - synthType.defaultOnlyType = type_4; + var type_5 = createDefaultPropertyWrapperForModule(symbol, originalSymbol); + synthType.defaultOnlyType = type_5; } return synthType.defaultOnlyType; } @@ -75449,6 +75998,10 @@ var ts; return restParameter.escapedName; } function getParameterIdentifierNameAtPosition(signature, pos) { + var _a; + if (((_a = signature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 315 /* JSDocFunctionType */) { + return undefined; + } var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { var param = signature.parameters[pos]; @@ -75690,27 +76243,28 @@ var ts; var links = getSymbolLinks(parameter); if (!links.type) { var declaration = parameter.valueDeclaration; - links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true); + links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); if (declaration.name.kind !== 79 /* Identifier */) { // if inference didn't come up with anything but unknown, fall back to the binding pattern if present. if (links.type === unknownType) { links.type = getTypeFromBindingPattern(declaration.name); } - assignBindingElementTypes(declaration.name); + assignBindingElementTypes(declaration.name, links.type); } } } // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push // the destructured type into the contained binding elements. - function assignBindingElementTypes(pattern) { + function assignBindingElementTypes(pattern, parentType) { for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { + var type = getBindingElementTypeFromParentType(element, parentType); if (element.name.kind === 79 /* Identifier */) { - getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); + getSymbolLinks(getSymbolOfNode(element)).type = type; } else { - assignBindingElementTypes(element.name); + assignBindingElementTypes(element.name, type); } } } @@ -75963,12 +76517,12 @@ var ts; var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false); // notEqualFacts states that the type of the switched value is not equal to every type in the switch. var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); - var type_5 = getBaseConstraintOfType(operandType) || operandType; + var type_6 = getBaseConstraintOfType(operandType) || operandType; // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types. - if (type_5.flags & 3 /* AnyOrUnknown */) { + if (type_6.flags & 3 /* AnyOrUnknown */) { return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */; } - return !!(filterType(type_5, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); + return !!(filterType(type_6, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */); } var type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { @@ -77421,11 +77975,11 @@ var ts; } } function checkExpressionCached(node, checkMode) { + if (checkMode && checkMode !== 0 /* Normal */) { + return checkExpression(node, checkMode); + } var links = getNodeLinks(node); if (!links.resolvedType) { - if (checkMode && checkMode !== 0 /* Normal */) { - return checkExpression(node, checkMode); - } // When computing a type that we're going to cache, we need to ignore any ongoing control flow // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart // to the top of the stack ensures all transient types are computed from a known point. @@ -77445,10 +77999,12 @@ var ts; node.kind === 228 /* AsExpression */ || ts.isJSDocTypeAssertion(node); } - function checkDeclarationInitializer(declaration, contextualType) { + function checkDeclarationInitializer(declaration, checkMode, contextualType) { var initializer = ts.getEffectiveInitializer(declaration); var type = getQuickTypeOfExpression(initializer) || - (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer)); + (contextualType ? + checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, checkMode || 0 /* Normal */) + : checkExpressionCached(initializer, checkMode)); return ts.isParameter(declaration) && declaration.name.kind === 201 /* ArrayBindingPattern */ && isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ? padTupleType(type, declaration.name) : type; @@ -77763,7 +78319,7 @@ var ts; } } function checkExpression(node, checkMode, forceTuple) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -78088,6 +78644,7 @@ var ts; } } checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node)); + checkUnmatchedJSDocParameters(node); ts.forEach(node.parameters, checkParameter); // TODO(rbuckton): Should we start checking JSDoc types? if (node.type) { @@ -78318,9 +78875,6 @@ var ts; checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); - if (ts.isPrivateIdentifier(node.name) && ts.hasStaticModifier(node) && node.initializer && languageVersion === 99 /* ESNext */ && !compilerOptions.useDefineForClassFields) { - error(node.initializer, ts.Diagnostics.Static_fields_with_private_names_can_t_have_initializers_when_the_useDefineForClassFields_flag_is_not_specified_with_a_target_of_esnext_Consider_adding_the_useDefineForClassFields_flag); - } // property signatures already report "initializer not allowed in ambient context" elsewhere if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 166 /* PropertyDeclaration */ && node.initializer) { error(node, ts.Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); @@ -78409,32 +78963,38 @@ var ts; if (classExtendsNull) { error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } - // The first statement in the body of a constructor (excluding prologue directives) must be a super call - // if both of the following are true: + // A super call must be root-level in a constructor if both of the following are true: // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - var superCallShouldBeFirst = (ts.getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && + var superCallShouldBeRootLevel = (ts.getEmitScriptTarget(compilerOptions) !== 99 /* ESNext */ || !useDefineForClassFields) && (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 16476 /* ParameterPropertyModifier */); })); - // Skip past any prologue directives to find the first statement - // to ensure that it was a super call. - if (superCallShouldBeFirst) { - var statements = node.body.statements; - var superCallStatement = void 0; - for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) { - var statement = statements_4[_i]; - if (statement.kind === 237 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { - superCallStatement = statement; - break; + if (superCallShouldBeRootLevel) { + // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional + // See GH #8277 + if (!superCallIsRootLevelInConstructor(superCall, node.body)) { + error(superCall, ts.Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers); + } + // Skip past any prologue directives to check statements for referring to 'super' or 'this' before a super call + else { + var superCallStatement = void 0; + for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isExpressionStatement(statement) && ts.isSuperCall(ts.skipOuterExpressions(statement.expression))) { + superCallStatement = statement; + break; + } + if (!ts.isPrologueDirective(statement) && nodeImmediatelyReferencesSuperOrThis(statement)) { + break; + } } - if (!ts.isPrologueDirective(statement)) { - break; + // Until we have better flow analysis, it is an error to place the super call within any kind of block or conditional + // See GH #8277 + if (superCallStatement === undefined) { + error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers); } } - if (!superCallStatement) { - error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_parameter_properties_or_private_identifiers); - } } } else if (!classExtendsNull) { @@ -78442,6 +79002,19 @@ var ts; } } } + function superCallIsRootLevelInConstructor(superCall, body) { + var superCallParent = ts.walkUpParenthesizedExpressions(superCall.parent); + return ts.isExpressionStatement(superCallParent) && superCallParent.parent === body; + } + function nodeImmediatelyReferencesSuperOrThis(node) { + if (node.kind === 106 /* SuperKeyword */ || node.kind === 108 /* ThisKeyword */) { + return true; + } + if (ts.isThisContainerOrFunctionBlock(node)) { + return false; + } + return !!ts.forEachChild(node, nodeImmediatelyReferencesSuperOrThis); + } function checkAccessorDeclaration(node) { if (produceDiagnostics) { // Grammar checking accessors @@ -79432,28 +80005,24 @@ var ts; if (returnType.flags & 1 /* Any */) { return; } + var headMessage; var expectedReturnType; - var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); - var errorInfo; switch (node.parent.kind) { case 256 /* ClassDeclaration */: + headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var classSymbol = getSymbolOfNode(node.parent); var classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; - case 163 /* Parameter */: - expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any); - break; case 166 /* PropertyDeclaration */: + case 163 /* Parameter */: + headMessage = ts.Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; expectedReturnType = voidType; - errorInfo = ts.chainDiagnosticMessages( - /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any); break; case 168 /* MethodDeclaration */: case 171 /* GetAccessor */: case 172 /* SetAccessor */: + headMessage = ts.Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; var methodType = getTypeOfNode(node.parent); var descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); @@ -79461,7 +80030,7 @@ var ts; default: return ts.Debug.fail(); } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -79643,31 +80212,6 @@ var ts; } function checkJSDocParameterTag(node) { checkSourceElement(node.typeExpression); - if (!ts.getParameterSymbolFromJSDoc(node)) { - var decl = ts.getHostSignatureFromJSDoc(node); - // don't issue an error for invalid hosts -- just functions -- - // and give a better error message when the host function mentions `arguments` - // but the tag doesn't have an array type - if (decl) { - var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node); - if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) { - return; - } - if (!containsArgumentsReference(decl)) { - if (ts.isQualifiedName(node.name)) { - error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); - } - else { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); - } - } - else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && - node.typeExpression && node.typeExpression.type && - !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 160 /* QualifiedName */ ? node.name.right : node.name)); - } - } - } } function checkJSDocPropertyTag(node) { checkSourceElement(node.typeExpression); @@ -80369,7 +80913,8 @@ var ts; } // check private/protected variable access var parent = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent); + var parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */; + var parentType = getTypeForBindingElementParent(parent, parentCheckMode); var name = node.propertyName || node.name; if (parentType && !ts.isBindingPattern(name)) { var exprType = getLiteralTypeFromPropertyName(name); @@ -80425,7 +80970,7 @@ var ts; } // For a commonjs `const x = require`, validate the alias and exit var symbol = getSymbolOfNode(node); - if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node)) { + if (symbol.flags & 2097152 /* Alias */ && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(node)) { checkAliasSymbol(node); return; } @@ -80503,7 +81048,7 @@ var ts; return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags); } function checkVariableDeclaration(node) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); checkGrammarVariableDeclaration(node); checkVariableLikeDeclaration(node); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); @@ -81608,7 +82153,7 @@ var ts; var declaration = catchClause.variableDeclaration; var typeNode = ts.getEffectiveTypeAnnotationNode(ts.getRootDeclaration(declaration)); if (typeNode) { - var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false); + var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false, 0 /* Normal */); if (type && !(type.flags & 3 /* AnyOrUnknown */)) { grammarErrorOnFirstToken(typeNode, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified); } @@ -81739,6 +82284,47 @@ var ts; error(name, ts.Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ts.ModuleKind[moduleKind]); // https://github.com/Microsoft/TypeScript/issues/17494 } } + function checkUnmatchedJSDocParameters(node) { + var jsdocParameters = ts.filter(ts.getJSDocTags(node), ts.isJSDocParameterTag); + if (!ts.length(jsdocParameters)) + return; + var isJs = ts.isInJSFile(node); + var parameters = new ts.Set(); + var excludedParameters = new ts.Set(); + ts.forEach(node.parameters, function (_a, index) { + var name = _a.name; + if (ts.isIdentifier(name)) { + parameters.add(name.escapedText); + } + if (ts.isBindingPattern(name)) { + excludedParameters.add(index); + } + }); + var containsArguments = containsArgumentsReference(node); + if (containsArguments) { + var lastJSDocParam = ts.lastOrUndefined(jsdocParameters); + if (isJs && lastJSDocParam && ts.isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && + lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) { + error(lastJSDocParam.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(lastJSDocParam.name)); + } + } + else { + ts.forEach(jsdocParameters, function (_a, index) { + var name = _a.name; + if (excludedParameters.has(index) || ts.isIdentifier(name) && parameters.has(name.escapedText)) { + return; + } + if (ts.isQualifiedName(name)) { + if (isJs) { + error(name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(name), ts.entityNameToString(name.left)); + } + } + else { + errorOrSuggestion(isJs, name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(name)); + } + }); + } + } /** * Check each type parameter and check that type parameters have no duplicate type parameter declarations */ @@ -82302,7 +82888,7 @@ var ts; for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) { var prop = properties_4[_a]; var existing = seen.get(prop.escapedName); - if (existing && !isPropertyIdenticalTo(existing, prop)) { + if (existing && prop.parent === existing.parent) { seen.delete(prop.escapedName); } } @@ -82470,7 +83056,7 @@ var ts; } else { var text = ts.getTextOfPropertyName(member.name); - if (isNumericLiteralName(text) && !ts.isInfinityOrNaNString(text)) { + if (ts.isNumericLiteralName(text) && !ts.isInfinityOrNaNString(text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } } @@ -82576,16 +83162,15 @@ var ts; return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText); case 206 /* ElementAccessExpression */: case 205 /* PropertyAccessExpression */: - var ex = expr; - if (isConstantMemberAccess(ex)) { - var type = getTypeOfExpression(ex.expression); + if (isConstantMemberAccess(expr)) { + var type = getTypeOfExpression(expr.expression); if (type.symbol && type.symbol.flags & 384 /* Enum */) { var name = void 0; - if (ex.kind === 205 /* PropertyAccessExpression */) { - name = ex.name.escapedText; + if (expr.kind === 205 /* PropertyAccessExpression */) { + name = expr.name.escapedText; } else { - name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text); + name = ts.escapeLeadingUnderscores(ts.cast(expr.argumentExpression, ts.isLiteralExpression).text); } return evaluateEnumMember(expr, type.symbol, name); } @@ -82599,7 +83184,7 @@ var ts; if (memberSymbol) { var declaration = memberSymbol.valueDeclaration; if (declaration !== member) { - if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member)) { + if (declaration && isBlockScopedNameDeclaredBeforeUse(declaration, member) && ts.isEnumDeclaration(declaration.parent)) { return getEnumMemberValue(declaration); } error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums); @@ -82613,6 +83198,10 @@ var ts; } } function isConstantMemberAccess(node) { + var type = getTypeOfExpression(node); + if (type === errorType) { + return false; + } return node.kind === 79 /* Identifier */ || node.kind === 205 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) || node.kind === 206 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) && @@ -82711,7 +83300,7 @@ var ts; var isAmbientExternalModule = ts.isAmbientModule(node); var contextErrorMessage = isAmbientExternalModule ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file - : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; + : ts.Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors. return; @@ -82893,10 +83482,20 @@ var ts; return false; } } + if (!ts.isImportEqualsDeclaration(node) && node.assertClause) { + var hasError = false; + for (var _i = 0, _a = node.assertClause.elements; _i < _a.length; _i++) { + var clause = _a[_i]; + if (!ts.isStringLiteral(clause.value)) { + hasError = true; + error(clause.value, ts.Diagnostics.Import_assertion_values_must_be_string_literal_expressions); + } + } + return !hasError; + } return true; } function checkAliasSymbol(node) { - var _a; var symbol = getSymbolOfNode(node); var target = resolveAlias(symbol); if (target !== unknownSymbol) { @@ -82934,6 +83533,9 @@ var ts; var name = ts.idText(node.kind === 269 /* ImportSpecifier */ ? node.propertyName || node.name : node.name); addTypeOnlyDeclarationRelatedInfo(error(node, message, name), isType ? undefined : typeOnlyAlias, name); } + if (isType && node.kind === 264 /* ImportEqualsDeclaration */ && ts.hasEffectiveModifier(node, 1 /* Export */)) { + error(node, ts.Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_the_isolatedModules_flag_is_provided); + } break; } case 274 /* ExportSpecifier */: { @@ -82952,10 +83554,45 @@ var ts; } } } - if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) { - addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName); + if (ts.isImportSpecifier(node)) { + var targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); + if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); + } + } + } + } + function isDeprecatedAliasedSymbol(symbol) { + return !!symbol.declarations && ts.every(symbol.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }); + } + function checkDeprecatedAliasedSymbol(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */)) + return symbol; + var targetSymbol = resolveAlias(symbol); + if (targetSymbol === unknownSymbol) + return targetSymbol; + while (symbol.flags & 2097152 /* Alias */) { + var target = getImmediateAliasedSymbol(symbol); + if (target) { + if (target === targetSymbol) + break; + if (target.declarations && ts.length(target.declarations)) { + if (isDeprecatedAliasedSymbol(target)) { + addDeprecatedSuggestion(location, target.declarations, target.escapedName); + break; + } + else { + if (symbol === targetSymbol) + break; + symbol = target; + } + } + } + else { + break; } } + return targetSymbol; } function checkImportBinding(node) { checkCollisionsForDeclarationName(node, node.name); @@ -82970,8 +83607,11 @@ var ts; function checkAssertClause(declaration) { var _a; if (declaration.assertClause) { - if (moduleKind !== ts.ModuleKind.ESNext) { - return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext); + var mode = (moduleKind === ts.ModuleKind.NodeNext) && declaration.moduleSpecifier && getUsageModeForExpression(declaration.moduleSpecifier); + if (mode !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.ESNext) { + return grammarErrorOnNode(declaration.assertClause, moduleKind === ts.ModuleKind.NodeNext + ? ts.Diagnostics.Import_assertions_are_not_allowed_on_statements_that_transpile_to_commonjs_require_calls + : ts.Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_or_nodenext); } if (ts.isImportDeclaration(declaration) ? (_a = declaration.importClause) === null || _a === void 0 ? void 0 : _a.isTypeOnly : declaration.isTypeOnly) { return grammarErrorOnNode(declaration.assertClause, ts.Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports); @@ -82979,7 +83619,7 @@ var ts; } } function checkImportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } @@ -83012,7 +83652,7 @@ var ts; checkAssertClause(node); } function checkImportEqualsDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } @@ -83049,7 +83689,7 @@ var ts; } } function checkExportDeclaration(node) { - if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { + if (checkGrammarModuleElementContext(node, ts.isInJSFile(node) ? ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } @@ -83261,9 +83901,9 @@ var ts; } } // Checks for export * conflicts - var exports_2 = getExportsOfModule(moduleSymbol); - if (exports_2) { - exports_2.forEach(function (_a, id) { + var exports_3 = getExportsOfModule(moduleSymbol); + if (exports_3) { + exports_3.forEach(function (_a, id) { var declarations = _a.declarations, flags = _a.flags; if (id === "__export") { return; @@ -83572,9 +84212,8 @@ var ts; var enclosingFile = ts.getSourceFileOfNode(node); var links = getNodeLinks(enclosingFile); if (!(links.flags & 1 /* TypeChecked */)) { - links.deferredNodes = links.deferredNodes || new ts.Map(); - var id = getNodeId(node); - links.deferredNodes.set(id, node); + links.deferredNodes || (links.deferredNodes = new ts.Set()); + links.deferredNodes.add(node); } } function checkDeferredNodes(context) { @@ -83584,7 +84223,7 @@ var ts; } } function checkDeferredNode(node) { - ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end }); + ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath }); var saveCurrentNode = currentNode; currentNode = node; instantiationCount = 0; @@ -84144,7 +84783,10 @@ var ts; case 80 /* PrivateIdentifier */: case 205 /* PropertyAccessExpression */: case 160 /* QualifiedName */: - return getSymbolOfNameOrPropertyAccessExpression(node); + if (!ts.isThisInTypeQuery(node)) { + return getSymbolOfNameOrPropertyAccessExpression(node); + } + // falls through case 108 /* ThisKeyword */: var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); if (ts.isFunctionLike(container)) { @@ -84281,7 +84923,7 @@ var ts; return errorType; } if (ts.isBindingPattern(node)) { - return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType; + return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true, 0 /* Normal */) || errorType; } if (isInRightSideOfImportOrExportAssignment(node)) { var symbol = getSymbolAtLocation(node); @@ -84620,7 +85262,7 @@ var ts; if (!symbol) { return false; } - var target = resolveAlias(symbol); + var target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) { return true; } @@ -85389,7 +86031,7 @@ var ts; if (quickResult !== undefined) { return quickResult; } - var lastStatic, lastDeclare, lastAsync, lastReadonly, lastOverride; + var lastStatic, lastDeclare, lastAsync, lastOverride; var flags = 0 /* None */; for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) { var modifier = _a[_i]; @@ -85493,7 +86135,6 @@ var ts; return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature); } flags |= 64 /* Readonly */; - lastReadonly = modifier; break; case 93 /* ExportKeyword */: if (flags & 1 /* Export */) { @@ -85606,18 +86247,12 @@ var ts; if (flags & 32 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 128 /* Abstract */) { - return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217 - } if (flags & 16384 /* Override */) { return grammarErrorOnNode(lastOverride, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override"); // TODO: GH#18217 } - else if (flags & 256 /* Async */) { + if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } - else if (flags & 64 /* Readonly */) { - return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly"); - } return false; } else if ((node.kind === 265 /* ImportDeclaration */ || node.kind === 264 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { @@ -85853,20 +86488,6 @@ var ts; } return false; } - function checkGrammarForOmittedArgument(args) { - if (args) { - for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { - var arg = args_4[_i]; - if (arg.kind === 226 /* OmittedExpression */) { - return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); - } - } - } - return false; - } - function checkGrammarArguments(args) { - return checkGrammarForOmittedArgument(args); - } function checkGrammarHeritageClause(node) { var types = node.types; if (checkGrammarForDisallowedTrailingComma(types)) { @@ -85984,15 +86605,14 @@ var ts; if (prop.kind === 295 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) { // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern // outside of destructuring it is a syntax error - return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); + grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern); } if (name.kind === 80 /* PrivateIdentifier */) { grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies); } // Modifiers are never allowed on properties except for 'async' on a method declaration if (prop.modifiers) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion - for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955 + for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { var mod = _c[_b]; if (mod.kind !== 131 /* AsyncKeyword */ || prop.kind !== 168 /* MethodDeclaration */) { grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod)); @@ -86042,9 +86662,12 @@ var ts; seen.set(effectiveName, currentKind); } else { - if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) { + if ((currentKind & 8 /* Method */) && (existingKind & 8 /* Method */)) { grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name)); } + else if ((currentKind & 4 /* PropertyAssignment */) && (existingKind & 4 /* PropertyAssignment */)) { + grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name, ts.getTextOfNode(name)); + } else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) { if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) { seen.set(effectiveName, currentKind | existingKind); @@ -86742,18 +87365,22 @@ var ts; return false; } function checkNumericLiteralValueSize(node) { + // We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "." + // e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`. + var isFractional = ts.getTextOfNode(node).indexOf(".") !== -1; + var isScientific = node.numericLiteralFlags & 16 /* Scientific */; // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint - // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1 // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway - if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) { + if (isFractional || isScientific) { return; } - // We can't rely on the runtime to accurately store and compare extremely large numeric values - // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298 - // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER, - // it's likely addition operations on it will fail too - var apparentValue = +ts.getTextOfNode(node); - if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) { + // Here `node` is guaranteed to be a numeric literal representing an integer. + // We need to judge whether the integer `node` represents is <= 2 ** 53 - 1, which can be accomplished by comparing to `value` defined below because: + // 1) when `node` represents an integer <= 2 ** 53 - 1, `node.text` is its exact string representation and thus `value` precisely represents the integer. + // 2) otherwise, although `node.text` may be imprecise string representation, its mathematical value and consequently `value` cannot be less than 2 ** 53, + // thus the result of the predicate won't be affected. + var value = +node.text; + if (value <= Math.pow(2, 53) - 1) { return; } addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers)); @@ -86818,12 +87445,12 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); } var nodeArguments = node.arguments; - if (moduleKind !== ts.ModuleKind.ESNext) { + if (moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.NodeNext) { // We are allowed trailing comma after proposal-import-assertions. checkGrammarForDisallowedTrailingComma(nodeArguments); if (nodeArguments.length > 1) { var assertionArgument = nodeArguments[1]; - return grammarErrorOnNode(assertionArgument, ts.Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext); + return grammarErrorOnNode(assertionArgument, ts.Diagnostics.Dynamic_imports_only_support_a_second_argument_when_the_module_option_is_set_to_esnext_or_nodenext); } } if (nodeArguments.length === 0 || nodeArguments.length > 2) { @@ -86869,28 +87496,27 @@ var ts; } function findMostOverlappyType(source, unionTarget) { var bestMatch; - var matchingCount = 0; - for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { - var target = _a[_i]; - var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); - if (overlap.flags & 4194304 /* Index */) { - // perfect overlap of keys - bestMatch = target; - matchingCount = Infinity; - } - else if (overlap.flags & 1048576 /* Union */) { - // We only want to account for literal types otherwise. - // If we have a union of index types, it seems likely that we - // needed to elaborate between two generic mapped types anyway. - var len = ts.length(ts.filter(overlap.types, isUnitType)); - if (len >= matchingCount) { - bestMatch = target; - matchingCount = len; - } - } - else if (isUnitType(overlap) && 1 >= matchingCount) { - bestMatch = target; - matchingCount = 1; + if (!(source.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target = _a[_i]; + if (!(target.flags & (131068 /* Primitive */ | 406847488 /* InstantiablePrimitive */))) { + var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + return target; + } + else if (isUnitType(overlap) || overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = overlap.flags & 1048576 /* Union */ ? ts.countWhere(overlap.types, isUnitType) : 1; + if (len >= matchingCount) { + bestMatch = target; + matchingCount = len; + } + } + } } } return bestMatch; @@ -87526,7 +88152,7 @@ var ts; return factory.updateAssertClause(node, nodesVisitor(node.elements, visitor, ts.isAssertEntry), node.multiLine); case 293 /* AssertEntry */: ts.Debug.type(node); - return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isStringLiteral)); + return factory.updateAssertEntry(node, nodeVisitor(node.name, visitor, ts.isAssertionKey), nodeVisitor(node.value, visitor, ts.isExpressionNode)); case 266 /* ImportClause */: ts.Debug.type(node); return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings)); @@ -88570,34 +89196,31 @@ var ts; } ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment; /** - * Adds super call and preceding prologue directives into the list of statements. - * - * @param ctor The constructor node. - * @param result The list of statements. - * @param visitor The visitor to apply to each node added to the result array. - * @returns index of the statement that follows super call + * @returns Contained super() call from descending into the statement ignoring parentheses, if that call exists. + */ + function getSuperCallFromStatement(statement) { + if (!ts.isExpressionStatement(statement)) { + return undefined; + } + var expression = ts.skipParentheses(statement.expression); + return ts.isSuperCall(expression) + ? expression + : undefined; + } + ts.getSuperCallFromStatement = getSuperCallFromStatement; + /** + * @returns The index (after prologue statements) of a super call, or -1 if not found. */ - function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) { - if (ctor.body) { - var statements = ctor.body.statements; - // add prologue directives to the list (if any) - var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor); - if (index === statements.length) { - // list contains nothing but prologue directives (or empty) - exit - return index; - } - var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index); - if (superIndex > -1) { - for (var i = index; i <= superIndex; i++) { - result.push(ts.visitNode(statements[i], visitor, ts.isStatement)); - } - return superIndex + 1; + function findSuperStatementIndex(statements, indexAfterLastPrologueStatement) { + for (var i = indexAfterLastPrologueStatement; i < statements.length; i += 1) { + var statement = statements[i]; + if (getSuperCallFromStatement(statement)) { + return i; } - return index; } - return 0; + return -1; } - ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall; + ts.findSuperStatementIndex = findSuperStatementIndex; function getProperties(node, requireInitializer, isStatic) { return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); }); } @@ -90215,7 +90838,7 @@ var ts; // ], C.prototype, "prop"); // var prefix = getClassMemberPrefix(node, member); - var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true); + var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !ts.hasSyntacticModifier(member, 2 /* Ambient */)); var descriptor = languageVersion > 0 /* ES3 */ ? member.kind === 166 /* PropertyDeclaration */ // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it @@ -90496,6 +91119,7 @@ var ts; case 176 /* TypePredicate */: case 133 /* BooleanKeyword */: return factory.createIdentifier("Boolean"); + case 197 /* TemplateLiteralType */: case 149 /* StringKeyword */: return factory.createIdentifier("String"); case 147 /* ObjectKeyword */: @@ -90834,10 +91458,14 @@ var ts; return ts.visitFunctionBody(body, visitor, context); } var statements = []; - var indexOfFirstStatement = 0; resumeLexicalEnvironment(); - indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor); - // Add parameters with property assignments. Transforms this: + var indexAfterLastPrologueStatement = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor); + var superStatementIndex = ts.findSuperStatementIndex(body.statements, indexAfterLastPrologueStatement); + // If there was a super call, visit existing statements up to and including it + if (superStatementIndex >= 0) { + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexAfterLastPrologueStatement, superStatementIndex + 1 - indexAfterLastPrologueStatement)); + } + // Transform parameters into property assignments. Transforms this: // // constructor (public x, public y) { // } @@ -90849,9 +91477,17 @@ var ts; // this.y = y; // } // - ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment)); - // Add the existing statements, skipping the initial super call. - ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + var parameterPropertyAssignments = ts.mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment); + // If there is a super() call, the parameter properties go immediately after it + if (superStatementIndex >= 0) { + ts.addRange(statements, parameterPropertyAssignments); + } + // Since there was no super() call, parameter properties are the first statements in the constructor + else { + statements = ts.addRange(parameterPropertyAssignments, statements); + } + // Add remaining statements from the body, skipping the super() call if it was found + ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, superStatementIndex + 1)); // End the lexical environment. statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true); @@ -91029,11 +91665,10 @@ var ts; // we can safely elide the parentheses here, as a new synthetic // ParenthesizedExpression will be inserted if we remove parentheses too // aggressively. - // HOWEVER - if there are leading comments on the expression itself, to handle ASI - // correctly for return and throw, we must keep the parenthesis - if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) { - return factory.updateParenthesizedExpression(node, expression); - } + // + // If there are leading comments on the expression itself, the emitter will handle ASI + // for return, throw, and yield by re-introducing parenthesis during emit on an as-need + // basis. return factory.createPartiallyEmittedExpression(expression, node); } return ts.visitEachChild(node, visitor, context); @@ -91943,11 +92578,13 @@ var ts; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var useDefineForClassFields = ts.getUseDefineForClassFields(compilerOptions); - var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 99 /* ESNext */; + var shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* ES2022 */; + // We need to transform `this` in a static initializer into a reference to the class + // when targeting < ES2022 since the assignment will be moved outside of the class body. + var shouldTransformThisInStaticInitializers = languageVersion < 9 /* ES2022 */; // We don't need to transform `super` property access when targeting ES5, ES3 because // the es2015 transformation handles those. - var shouldTransformSuperInStaticInitializers = (languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields) && languageVersion >= 2 /* ES2015 */; - var shouldTransformThisInStaticInitializers = languageVersion <= 8 /* ES2021 */ || !useDefineForClassFields; + var shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= 2 /* ES2015 */; var previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -91973,7 +92610,7 @@ var ts; function transformSourceFile(node) { var options = context.getCompilerOptions(); if (node.isDeclarationFile - || useDefineForClassFields && ts.getEmitScriptTarget(options) === 99 /* ESNext */) { + || useDefineForClassFields && ts.getEmitScriptTarget(options) >= 9 /* ES2022 */) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -92176,6 +92813,10 @@ var ts; ts.Debug.assert(!ts.some(node.decorators)); if (ts.isPrivateIdentifier(node.name)) { if (!shouldTransformPrivateElementsOrClassStaticBlocks) { + if (ts.isStatic(node)) { + // static fields are left as is + return ts.visitEachChild(node, visitor, context); + } // Initializer is elided as the field is initialized in transformConstructor. return factory.updatePropertyDeclaration(node, /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, @@ -92197,6 +92838,22 @@ var ts; if (expr && !ts.isSimpleInlineableExpression(expr)) { getPendingExpressions().push(expr); } + if (ts.isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { + var initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis()); + if (initializerStatement) { + var staticBlock = factory.createClassStaticBlockDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, factory.createBlock([initializerStatement])); + ts.setOriginalNode(staticBlock, node); + ts.setCommentRange(staticBlock, node); + // Set the comment range for the statement to an empty synthetic range + // and drop synthetic comments from the statement to avoid printing them twice. + ts.setCommentRange(initializerStatement, { pos: -1, end: -1 }); + ts.setSyntheticLeadingComments(initializerStatement, undefined); + ts.setSyntheticTrailingComments(initializerStatement, undefined); + return staticBlock; + } + } return undefined; } function createPrivateIdentifierAccess(info, receiver) { @@ -92584,7 +93241,6 @@ var ts; if (facts & 8 /* NeedsSubstitutionForThisInClassStaticField */) { enableSubstitutionForClassStaticThisOrSuperReference(); } - var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); // If a class has private static fields, or a static field has a `this` or `super` reference, // then we need to allocate a temp variable to hold on to that reference. var pendingClassReferenceAssignment; @@ -92612,6 +93268,7 @@ var ts; // From ES6 specification: // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. + var staticProperties = ts.getStaticPropertiesAndClassStaticBlock(node); if (ts.some(staticProperties)) { addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node)); } @@ -92650,7 +93307,7 @@ var ts; } var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, heritageClauseVisitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass)); - var hasTransformableStatics = ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || (shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifier(p.name)); }); + var hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(staticPropertiesOrClassStaticBlocks, function (p) { return ts.isClassStaticBlockDeclaration(p) || !!p.initializer || ts.isPrivateIdentifier(p.name); }); if (hasTransformableStatics || ts.some(pendingExpressions)) { if (isDecoratedClassDeclaration) { ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration."); @@ -92697,6 +93354,7 @@ var ts; return undefined; } function transformClassMembers(node, isDerivedClass) { + var members = []; if (shouldTransformPrivateElementsOrClassStaticBlocks) { // Declare private names. for (var _i = 0, _a = node.members; _i < _a.length; _i++) { @@ -92709,12 +93367,20 @@ var ts; createBrandCheckWeakSetForPrivateMethods(); } } - var members = []; var constructor = transformConstructor(node, isDerivedClass); + var visitedMembers = ts.visitNodes(node.members, classElementVisitor, ts.isClassElement); if (constructor) { members.push(constructor); } - ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement)); + if (!shouldTransformPrivateElementsOrClassStaticBlocks && ts.some(pendingExpressions)) { + members.push(factory.createClassStaticBlockDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, factory.createBlock([ + factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)) + ]))); + pendingExpressions = undefined; + } + ts.addRange(members, visitedMembers); return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members); } function createBrandCheckWeakSetForPrivateMethods() { @@ -92730,7 +93396,7 @@ var ts; if (useDefineForClassFields) { // If we are using define semantics and targeting ESNext or higher, // then we don't need to transform any class properties. - return languageVersion < 99 /* ESNext */; + return languageVersion < 9 /* ES2022 */; } return ts.isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && ts.isPrivateIdentifierClassElementDeclaration(member); } @@ -92750,6 +93416,7 @@ var ts; /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor)); } function transformConstructorBody(node, constructor, isDerivedClass) { + var _a; var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false); if (!useDefineForClassFields) { properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); }); @@ -92761,9 +93428,21 @@ var ts; return ts.visitFunctionBody(/*node*/ undefined, visitor, context); } resumeLexicalEnvironment(); - var indexOfFirstStatement = 0; + var needsSyntheticConstructor = !constructor && isDerivedClass; + var indexOfFirstStatementAfterSuper = 0; + var prologueStatementCount = 0; + var superStatementIndex = -1; var statements = []; - if (!constructor && isDerivedClass) { + if ((_a = constructor === null || constructor === void 0 ? void 0 : constructor.body) === null || _a === void 0 ? void 0 : _a.statements) { + prologueStatementCount = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor); + superStatementIndex = ts.findSuperStatementIndex(constructor.body.statements, prologueStatementCount); + // If there was a super call, visit existing statements up to and including it + if (superStatementIndex >= 0) { + indexOfFirstStatementAfterSuper = superStatementIndex + 1; + statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, prologueStatementCount), true), ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, prologueStatementCount, indexOfFirstStatementAfterSuper - prologueStatementCount), true), statements.slice(prologueStatementCount), true); + } + } + if (needsSyntheticConstructor) { // Add a synthetic `super` call: // // super(...arguments); @@ -92771,9 +93450,6 @@ var ts; statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))]))); } - if (constructor) { - indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor); - } // Add the property initializers. Transforms this: // // public x = 1; @@ -92784,31 +93460,59 @@ var ts; // this.x = 1; // } // + // If we do useDefineForClassFields, they'll be converted elsewhere. + // We instead *remove* them from the transformed output at this stage. + var parameterPropertyDeclarationCount = 0; if (constructor === null || constructor === void 0 ? void 0 : constructor.body) { - var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement); - if (afterParameterProperties === -1) { - afterParameterProperties = constructor.body.statements.length; + if (useDefineForClassFields) { + statements = statements.filter(function (statement) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor); }); } - if (afterParameterProperties > indexOfFirstStatement) { - if (!useDefineForClassFields) { - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement)); + else { + for (var _i = 0, _b = constructor.body.statements; _i < _b.length; _i++) { + var statement = _b[_i]; + if (ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { + parameterPropertyDeclarationCount++; + } + } + if (parameterPropertyDeclarationCount > 0) { + var parameterProperties = ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatementAfterSuper, parameterPropertyDeclarationCount); + // If there was a super() call found, add parameter properties immediately after it + if (superStatementIndex >= 0) { + ts.addRange(statements, parameterProperties); + } + // If a synthetic super() call was added, add them just after it + else if (needsSyntheticConstructor) { + statements = __spreadArray(__spreadArray([ + statements[0] + ], parameterProperties, true), statements.slice(1), true); + } + // Since there wasn't a super() call, add them to the top of the constructor + else { + statements = __spreadArray(__spreadArray([], parameterProperties, true), statements, true); + } + indexOfFirstStatementAfterSuper += parameterPropertyDeclarationCount; } - indexOfFirstStatement = afterParameterProperties; } } var receiver = factory.createThis(); // private methods can be called in property initializers, they should execute first. addMethodStatements(statements, privateMethodsAndAccessors, receiver); addPropertyOrClassStaticBlockStatements(statements, properties, receiver); - // Add existing statements, skipping the initial super call. + // Add existing statements after the initial prologues and super call if (constructor) { - ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement)); + ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitBodyStatement, ts.isStatement, indexOfFirstStatementAfterSuper + prologueStatementCount)); } statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment()); return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ constructor ? constructor.body.statements : node.members), /*multiLine*/ true), /*location*/ constructor ? constructor.body : undefined); + function visitBodyStatement(statement) { + if (useDefineForClassFields && ts.isParameterPropertyDeclaration(ts.getOriginalNode(statement), constructor)) { + return undefined; + } + return visitor(statement); + } } /** * Generates assignment statements for property initializers. @@ -92819,19 +93523,34 @@ var ts; function addPropertyOrClassStaticBlockStatements(statements, properties, receiver) { for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; - var expression = ts.isClassStaticBlockDeclaration(property) ? - transformClassStaticBlockDeclaration(property) : - transformProperty(property, receiver); - if (!expression) { + if (ts.isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) { + continue; + } + var statement = transformPropertyOrClassStaticBlock(property, receiver); + if (!statement) { continue; } - var statement = factory.createExpressionStatement(expression); - ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - ts.setCommentRange(statement, property); - ts.setOriginalNode(statement, property); statements.push(statement); } } + function transformPropertyOrClassStaticBlock(property, receiver) { + var expression = ts.isClassStaticBlockDeclaration(property) ? + transformClassStaticBlockDeclaration(property) : + transformProperty(property, receiver); + if (!expression) { + return undefined; + } + var statement = factory.createExpressionStatement(expression); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); + ts.setOriginalNode(statement, property); + // `setOriginalNode` *copies* the `emitNode` from `property`, so now both + // `statement` and `expression` have a copy of the synthesized comments. + // Drop the comments from expression to avoid printing them twice. + ts.setSyntheticLeadingComments(expression, undefined); + ts.setSyntheticTrailingComments(expression, undefined); + return statement; + } /** * Generates assignment expressions for property initializers. * @@ -93523,7 +94242,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 128 /* ContainsES2017 */) === 0) { + if ((node.transformFlags & 256 /* ContainsES2017 */) === 0) { return node; } switch (node.kind) { @@ -94081,6 +94800,7 @@ var ts; var exportedVariableStatement = false; var enabledSubstitutions; var enclosingFunctionFlags; + var parametersWithPrecedingObjectRestOrSpread; var enclosingSuperContainerFlags = 0; var hierarchyFacts = 0; var currentSourceFile; @@ -94156,7 +94876,7 @@ var ts; * expression of an `ExpressionStatement`). */ function visitorWorker(node, expressionResultIsUnused) { - if ((node.transformFlags & 64 /* ContainsES2018 */) === 0) { + if ((node.transformFlags & 128 /* ContainsES2018 */) === 0) { return node; } switch (node.kind) { @@ -94239,7 +94959,7 @@ var ts; function visitYieldExpression(node) { if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) { if (node.asteriskToken) { - var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression); + var expression = ts.visitNode(ts.Debug.checkDefined(node.expression), visitor, ts.isExpression); return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression( /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node); } @@ -94537,6 +95257,7 @@ var ts; /*incrementor*/ undefined, /*statement*/ convertForOfStatementHead(node, getValue)), /*location*/ node), 256 /* NoTokenTrailingSourceMaps */); + ts.setOriginalNode(forStatement, node); return factory.createTryStatement(factory.createBlock([ factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement) ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([ @@ -94554,7 +95275,19 @@ var ts; ]), 1 /* SingleLine */)) ])); } + function parameterVisitor(node) { + ts.Debug.assertNode(node, ts.isParameter); + return visitParameter(node); + } function visitParameter(node) { + if (parametersWithPrecedingObjectRestOrSpread === null || parametersWithPrecedingObjectRestOrSpread === void 0 ? void 0 : parametersWithPrecedingObjectRestOrSpread.has(node)) { + return factory.updateParameterDeclaration(node, + /*decorators*/ undefined, + /*modifiers*/ undefined, node.dotDotDotToken, ts.isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name, + /*questionToken*/ undefined, + /*type*/ undefined, + /*initializer*/ undefined); + } if (node.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { // Binding patterns are converted into a generated name and are // evaluated inside the function body. @@ -94566,85 +95299,119 @@ var ts; } return ts.visitEachChild(node, visitor, context); } + function collectParametersWithPrecedingObjectRestOrSpread(node) { + var parameters; + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + if (parameters) { + parameters.add(parameter); + } + else if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + parameters = new ts.Set(); + } + } + return parameters; + } function visitConstructorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateConstructorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitGetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateGetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitSetAccessorDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; - enclosingFunctionFlags = 0 /* Normal */; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; + enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateSetAccessorDeclaration(node, - /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node)); + /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, parameterVisitor, context), transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitMethodDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateMethodDeclaration(node, /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitFunctionDeclaration(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateFunctionDeclaration(node, /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitArrowFunction(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateArrowFunction(node, node.modifiers, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function visitFunctionExpression(node) { var savedEnclosingFunctionFlags = enclosingFunctionFlags; + var savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread; enclosingFunctionFlags = ts.getFunctionFlags(node); + parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node); var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */ ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier) : node.modifiers, enclosingFunctionFlags & 2 /* Async */ ? undefined : node.asteriskToken, node.name, - /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), + /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, parameterVisitor, context), /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */ ? transformAsyncGeneratorFunctionBody(node) : transformFunctionBody(node)); enclosingFunctionFlags = savedEnclosingFunctionFlags; + parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread; return updated; } function transformAsyncGeneratorFunctionBody(node) { @@ -94705,16 +95472,71 @@ var ts; return body; } function appendObjectRestAssignmentsIfNeeded(statements, node) { + var containsPrecedingObjectRestOrSpread = false; for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { - var temp = factory.getGeneratedNameForNode(parameter); - var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, + if (containsPrecedingObjectRestOrSpread) { + if (ts.isBindingPattern(parameter.name)) { + // In cases where a binding pattern is simply '[]' or '{}', + // we usually don't want to emit a var declaration; however, in the presence + // of an initializer, we must emit that expression to preserve side effects. + // + // NOTE: see `insertDefaultValueAssignmentForBindingPattern` in es2015.ts + if (parameter.name.elements.length > 0) { + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)); + if (ts.some(declarations)) { + var declarationList = factory.createVariableDeclarationList(declarations); + var statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + else if (parameter.initializer) { + var name = factory.getGeneratedNameForNode(parameter); + var initializer = ts.visitNode(parameter.initializer, visitor, ts.isExpression); + var assignment = factory.createAssignment(name, initializer); + var statement = factory.createExpressionStatement(assignment); + ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); + statements = ts.append(statements, statement); + } + } + else if (parameter.initializer) { + // Converts a parameter initializer into a function body statement, i.e.: + // + // function f(x = 1) { } + // + // becomes + // + // function f(x) { + // if (typeof x === "undefined") { x = 1; } + // } + var name = factory.cloneNode(parameter.name); + ts.setTextRange(name, parameter.name); + ts.setEmitFlags(name, 48 /* NoSourceMap */); + var initializer = ts.visitNode(parameter.initializer, visitor, ts.isExpression); + ts.addEmitFlags(initializer, 48 /* NoSourceMap */ | 1536 /* NoComments */); + var assignment = factory.createAssignment(name, initializer); + ts.setTextRange(assignment, parameter); + ts.setEmitFlags(assignment, 1536 /* NoComments */); + var block = factory.createBlock([factory.createExpressionStatement(assignment)]); + ts.setTextRange(block, parameter); + ts.setEmitFlags(block, 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */); + var typeCheck = factory.createTypeCheck(factory.cloneNode(parameter.name), "undefined"); + var statement = factory.createIfStatement(typeCheck, block); + ts.startOnNewLine(statement); + ts.setTextRange(statement, parameter); + ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */); + statements = ts.append(statements, statement); + } + } + else if (parameter.transformFlags & 32768 /* ContainsObjectRestOrSpread */) { + containsPrecedingObjectRestOrSpread = true; + var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, factory.getGeneratedNameForNode(parameter), /*doNotRecordTempVariablesInLine*/ false, /*skipInitializer*/ true); if (ts.some(declarations)) { - var statement = factory.createVariableStatement( - /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations)); + var declarationList = factory.createVariableDeclarationList(declarations); + var statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList); ts.setEmitFlags(statement, 1048576 /* CustomPrologue */); statements = ts.append(statements, statement); } @@ -94853,7 +95675,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 32 /* ContainsES2019 */) === 0) { + if ((node.transformFlags & 64 /* ContainsES2019 */) === 0) { return node; } switch (node.kind) { @@ -94885,7 +95707,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 16 /* ContainsES2020 */) === 0) { + if ((node.transformFlags & 32 /* ContainsES2020 */) === 0) { return node; } switch (node.kind) { @@ -94981,11 +95803,11 @@ var ts; } function visitOptionalExpression(node, captureThisArg, isDelete) { var _a = flattenChain(node), expression = _a.expression, chain = _a.chain; - var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false); + var left = visitNonOptionalExpression(ts.skipPartiallyEmittedExpressions(expression), ts.isCallChain(chain[0]), /*isDelete*/ false); var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined; - var leftExpression = ts.isSyntheticReference(left) ? left.expression : left; - var capturedLeft = leftExpression; - if (!ts.isSimpleCopiableExpression(leftExpression)) { + var capturedLeft = ts.isSyntheticReference(left) ? left.expression : left; + var leftExpression = factory.restoreOuterExpressions(expression, capturedLeft, 8 /* PartiallyEmittedExpressions */); + if (!ts.isSimpleCopiableExpression(capturedLeft)) { capturedLeft = factory.createTempVariable(hoistVariableDeclaration); leftExpression = factory.createAssignment(capturedLeft, leftExpression); } @@ -95011,6 +95833,10 @@ var ts; break; case 207 /* CallExpression */: if (i === 0 && leftThisArg) { + if (!ts.isGeneratedIdentifier(leftThisArg)) { + leftThisArg = factory.cloneNode(leftThisArg); + ts.addEmitFlags(leftThisArg, 1536 /* NoComments */); + } rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 106 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression)); } else { @@ -95062,7 +95888,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 8 /* ContainsES2021 */) === 0) { + if ((node.transformFlags & 16 /* ContainsES2021 */) === 0) { return node; } switch (node.kind) { @@ -95164,11 +95990,11 @@ var ts; return existing.name; } if (!currentFileState.utilizedImplicitRuntimeImports) { - currentFileState.utilizedImplicitRuntimeImports = ts.createMap(); + currentFileState.utilizedImplicitRuntimeImports = new ts.Map(); } var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource); if (!specifierSourceImports) { - specifierSourceImports = ts.createMap(); + specifierSourceImports = new ts.Map(); currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports); } var generatedName = factory.createUniqueName("_".concat(name), 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */); @@ -95320,10 +96146,19 @@ var ts; var _a; var nonWhitespaceChildren = ts.getSemanticJsxChildren(children); var isStaticChildren = ts.length(nonWhitespaceChildren) > 1 || !!((_a = nonWhitespaceChildren[0]) === null || _a === void 0 ? void 0 : _a.dotDotDotToken); - var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)]; + var args = [tagName, objectProperties]; + // function jsx(type, config, maybeKey) {} + // "maybeKey" is optional. It is acceptable to use "_jsx" without a third argument + if (keyAttr) { + args.push(transformJsxAttributeInitializer(keyAttr.initializer)); + } if (compilerOptions.jsx === 5 /* ReactJSXDev */) { var originalFile = ts.getOriginalNode(currentSourceFile); if (originalFile && ts.isSourceFile(originalFile)) { + // "maybeKey" has to be replaced with "void 0" to not break the jsxDEV signature + if (keyAttr === undefined) { + args.push(factory.createVoidZero()); + } // isStaticChildren development flag args.push(isStaticChildren ? factory.createTrue() : factory.createFalse()); // __source development flag @@ -95826,7 +96661,7 @@ var ts; return ts.visitEachChild(node, visitor, context); } function visitor(node) { - if ((node.transformFlags & 256 /* ContainsES2016 */) === 0) { + if ((node.transformFlags & 512 /* ContainsES2016 */) === 0) { return node; } switch (node.kind) { @@ -96074,7 +96909,7 @@ var ts; || ts.isBlock(node)); } function shouldVisitNode(node) { - return (node.transformFlags & 512 /* ContainsES2015 */) !== 0 + return (node.transformFlags & 1024 /* ContainsES2015 */) !== 0 || convertedLoopState !== undefined || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node)) || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node)) @@ -96591,37 +97426,39 @@ var ts; var prologue = []; var statements = []; resumeLexicalEnvironment(); + // In derived classes, there may be code before the necessary super() call + // We'll remove pre-super statements to be tacked on after the rest of the body + var existingPrologue = ts.takeWhile(constructor.body.statements, ts.isPrologueDirective); + var _a = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue), superCall = _a.superCall, superStatementIndex = _a.superStatementIndex; + var postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1; // If a super call has already been synthesized, // we're going to assume that we should just transform everything after that. // The assumption is that no prior step in the pipeline has added any prologue directives. - var statementOffset = 0; + var statementOffset = postSuperStatementsStart; if (!hasSynthesizedSuper) - statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false); - addDefaultValueAssignmentsIfNeeded(statements, constructor); - addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false); if (!hasSynthesizedSuper) - statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor); - // If the first statement is a call to `super()`, visit the statement directly + statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ undefined); + // If there already exists a call to `super()`, visit the statement directly var superCallExpression; if (hasSynthesizedSuper) { superCallExpression = createDefaultSuperCallOrThis(); } - else if (isDerivedClass && statementOffset < constructor.body.statements.length) { - var firstStatement = constructor.body.statements[statementOffset]; - if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) { - superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression); - } + else if (superCall) { + superCallExpression = visitSuperCallInBody(superCall); } if (superCallExpression) { hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */; - statementOffset++; // skip this statement, we will add it after visiting the rest of the body. } + // Add parameter defaults at the beginning of the output, with prologue statements + addDefaultValueAssignmentsIfNeeded(prologue, constructor); + addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper); // visit the remaining statements ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset)); factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment()); insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false); - if (isDerivedClass) { - if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { + if (isDerivedClass || superCallExpression) { + if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & 8192 /* ContainsLexicalThis */)) { // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the // following representation: // @@ -96641,10 +97478,10 @@ var ts; // return C; // })(Base); // ``` - var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); + var superCall_1 = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression); var returnStatement = factory.createReturnStatement(superCallExpression); - ts.setCommentRange(returnStatement, ts.getCommentRange(superCall)); - ts.setEmitFlags(superCall, 1536 /* NoComments */); + ts.setCommentRange(returnStatement, ts.getCommentRange(superCall_1)); + ts.setEmitFlags(superCall_1, 1536 /* NoComments */); statements.push(returnStatement); } else { @@ -96669,9 +97506,19 @@ var ts; // return C; // })(Base); // ``` - // Since the `super()` call was the first statement, we insert the `this` capturing call to - // `super()` at the top of the list of `statements` (after any pre-existing custom prologues). - insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + // If the super() call is the first statement, we can directly create and assign its result to `_this` + if (superStatementIndex <= existingPrologue.length) { + insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis()); + } + // Since the `super()` call isn't the first statement, it's split across 1-2 statements: + // * A prologue `var _this = this;`, in case the constructor accesses this before super() + // * If it exists, a reassignment to that `_this` of the super() call + else { + insertCaptureThisForNode(prologue, constructor, createActualThis()); + if (superCallExpression) { + insertSuperThisCaptureThisForNode(statements, superCallExpression); + } + } if (!isSufficientlyCoveredByReturnStatements(constructor.body)) { statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */))); } @@ -96694,11 +97541,27 @@ var ts; // ``` insertCaptureThisForNodeIfNeeded(prologue, constructor); } - var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), + var body = factory.createBlock(ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], existingPrologue, true), prologue, true), (superStatementIndex <= existingPrologue.length ? ts.emptyArray : ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, existingPrologue.length, superStatementIndex)), true), statements, true)), /*location*/ constructor.body.statements), /*multiLine*/ true); - ts.setTextRange(block, constructor.body); - return block; + ts.setTextRange(body, constructor.body); + return body; + } + function findSuperCallAndStatementIndex(originalBodyStatements, existingPrologue) { + for (var i = existingPrologue.length; i < originalBodyStatements.length; i += 1) { + var superCall = ts.getSuperCallFromStatement(originalBodyStatements[i]); + if (superCall) { + // With a super() call, split the statements into pre-super() and 'body' (post-super()) + return { + superCall: superCall, + superStatementIndex: i, + }; + } + } + // Since there was no super() call found, consider all statements to be in the main 'body' (post-super()) + return { + superStatementIndex: -1, + }; } /** * We want to try to avoid emitting a return statement in certain cases if a user already returned something. @@ -96927,6 +97790,18 @@ var ts; } return false; } + /** + * Assigns the `this` in a constructor to the result of its `super()` call. + * + * @param statements Statements in the constructor body. + * @param superExpression Existing `super()` call for the constructor. + */ + function insertSuperThisCaptureThisForNode(statements, superExpression) { + enableSubstitutionsForCapturedThis(); + var assignSuperExpression = factory.createExpressionStatement(factory.createBinaryExpression(factory.createThis(), 63 /* EqualsToken */, superExpression)); + ts.insertStatementAfterCustomPrologue(statements, assignSuperExpression); + ts.setCommentRange(assignSuperExpression, ts.getOriginalNode(superExpression).parent); + } function insertCaptureThisForNode(statements, node, initializer) { enableSubstitutionsForCapturedThis(); var captureThisStatement = factory.createVariableStatement( @@ -97236,7 +98111,7 @@ var ts; if (ts.isBlock(body)) { // ensureUseStrict is false because no new prologue-directive should be added. // addStandardPrologue will put already-existing directives at the beginning of the target statement-array - statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false); + statementOffset = factory.copyStandardPrologue(body.statements, prologue, 0, /*ensureUseStrict*/ false); statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction); statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement); } @@ -97912,10 +98787,12 @@ var ts; // variables declared in the loop initializer that will be changed inside the loop var loopOutParameters = []; if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) { - var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node); + var hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) || + shouldConvertConditionOfForStatement(node) || + shouldConvertIncrementorOfForStatement(node); for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) { var decl = _a[_i]; - processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } } var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters }; @@ -98269,27 +99146,33 @@ var ts; caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements)); }); } - function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) { + function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead) { var name = decl.name; if (ts.isBindingPattern(name)) { for (var _i = 0, _a = name.elements; _i < _a.length; _i++) { var element = _a[_i]; if (!ts.isOmittedExpression(element)) { - processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer); + processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForHead); } } } else { loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name)); var checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) { + if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { var outParamName = factory.createUniqueName("out_" + ts.idText(name)); var flags = 0; if (checkFlags & 4194304 /* NeedsLoopOutParameter */) { flags |= 1 /* Body */; } - if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { - flags |= 2 /* Initializer */; + if (ts.isForStatement(container)) { + if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) { + flags |= 2 /* Initializer */; + } + if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) || + container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) { + flags |= 1 /* Body */; + } } loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName }); } @@ -98607,7 +99490,7 @@ var ts; /*type*/ undefined, factory.updateBlock(func.body, statements))), /*typeArguments*/ undefined, call.arguments)))); } - function visitImmediateSuperCallInBody(node) { + function visitSuperCallInBody(node) { return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); } function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { @@ -99387,7 +100270,7 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return ts.chainBundle(context, transformSourceFile); function transformSourceFile(node) { - if (node.isDeclarationFile || (node.transformFlags & 1024 /* ContainsGenerator */) === 0) { + if (node.isDeclarationFile || (node.transformFlags & 2048 /* ContainsGenerator */) === 0) { return node; } var visited = ts.visitEachChild(node, visitor, context); @@ -99410,7 +100293,7 @@ var ts; else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) { return visitGenerator(node); } - else if (transformFlags & 1024 /* ContainsGenerator */) { + else if (transformFlags & 2048 /* ContainsGenerator */) { return ts.visitEachChild(node, visitor, context); } else { @@ -99466,7 +100349,7 @@ var ts; if (node.transformFlags & 524288 /* ContainsYield */) { return visitJavaScriptContainingYield(node); } - else if (node.transformFlags & (1024 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { + else if (node.transformFlags & (2048 /* ContainsGenerator */ | 2097152 /* ContainsHoistedDeclarationOrCompletion */)) { return ts.visitEachChild(node, visitor, context); } else { @@ -102115,7 +102998,7 @@ var ts; function visitorWorker(node, valueIsDiscarded) { // This visitor does not need to descend into the tree if there is no dynamic import, destructuring assignment, or update expression // as export/import statements are only transformed at the top level of a file. - if (!(node.transformFlags & (4194304 /* ContainsDynamicImport */ | 2048 /* ContainsDestructuringAssignment */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4194304 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -103105,7 +103988,7 @@ var ts; if (ts.isIdentifier(node.expression)) { var expression = substituteExpressionIdentifier(node.expression); noSubstitution[ts.getNodeId(expression)] = true; - if (!ts.isIdentifier(expression)) { + if (!ts.isIdentifier(expression) && !(ts.getEmitFlags(node.expression) & 4096 /* HelperName */)) { return ts.addEmitFlags(factory.updateCallExpression(node, expression, /*typeArguments*/ undefined, node.arguments), 536870912 /* IndirectCall */); } @@ -103116,7 +103999,7 @@ var ts; if (ts.isIdentifier(node.tag)) { var tag = substituteExpressionIdentifier(node.tag); noSubstitution[ts.getNodeId(tag)] = true; - if (!ts.isIdentifier(tag)) { + if (!ts.isIdentifier(tag) && !(ts.getEmitFlags(node.tag) & 4096 /* HelperName */)) { return ts.addEmitFlags(factory.updateTaggedTemplateExpression(node, tag, /*typeArguments*/ undefined, node.template), 536870912 /* IndirectCall */); } @@ -104331,7 +105214,7 @@ var ts; * @param node The node to visit. */ function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (2048 /* ContainsDestructuringAssignment */ | 4194304 /* ContainsDynamicImport */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (4096 /* ContainsDestructuringAssignment */ | 4194304 /* ContainsDynamicImport */ | 67108864 /* ContainsUpdateExpressionForIdentifier */))) { return node; } switch (node.kind) { @@ -108763,6 +109646,7 @@ var ts; return emitJSDocSignature(node); case 325 /* JSDocTag */: case 330 /* JSDocClassTag */: + case 335 /* JSDocOverrideTag */: return emitJSDocSimpleTag(node); case 326 /* JSDocAugmentsTag */: case 327 /* JSDocImplementsTag */: @@ -108775,7 +109659,6 @@ var ts; case 332 /* JSDocPrivateTag */: case 333 /* JSDocProtectedTag */: case 334 /* JSDocReadonlyTag */: - case 335 /* JSDocOverrideTag */: return; case 336 /* JSDocCallbackTag */: return emitJSDocCallbackTag(node); @@ -109079,7 +109962,7 @@ var ts; emitPlaceholder(hint, node, snippet); break; case 0 /* TabStop */: - emitTabStop(snippet); + emitTabStop(hint, node, snippet); break; } } @@ -109089,7 +109972,10 @@ var ts; nonEscapingWrite("}"); // `}` // `${2:...}` } - function emitTabStop(snippet) { + function emitTabStop(hint, node, snippet) { + // A tab stop should only be attached to an empty node, i.e. a node that doesn't emit any text. + ts.Debug.assert(node.kind === 235 /* EmptyStatement */, "A tab stop cannot be attached to a node of kind ".concat(ts.Debug.formatSyntaxKind(node.kind), ".")); + ts.Debug.assert(hint !== 5 /* EmbeddedStatement */, "A tab stop cannot be attached to an embedded statement."); nonEscapingWrite("$".concat(snippet.order)); } // @@ -109793,7 +110679,7 @@ var ts; function emitYieldExpression(node) { emitTokenWithComment(125 /* YieldKeyword */, node.pos, writeKeyword, node); emit(node.asteriskToken); - emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma); } function emitSpreadElement(node) { emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node); @@ -109990,9 +110876,49 @@ var ts; } return pos; } + function commentWillEmitNewLine(node) { + return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; + } + function willEmitLeadingNewLine(node) { + if (!currentSourceFile) + return false; + if (ts.some(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine)) + return true; + if (ts.some(ts.getSyntheticLeadingComments(node), commentWillEmitNewLine)) + return true; + if (ts.isPartiallyEmittedExpression(node)) { + if (node.pos !== node.expression.pos) { + if (ts.some(ts.getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) + return true; + } + return willEmitLeadingNewLine(node.expression); + } + return false; + } + /** + * Wraps an expression in parens if we would emit a leading comment that would introduce a line separator + * between the node and its parent. + */ + function parenthesizeExpressionForNoAsi(node) { + if (!commentsDisabled && ts.isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) { + var parseNode = ts.getParseTreeNode(node); + if (parseNode && ts.isParenthesizedExpression(parseNode)) { + // If the original node was a parenthesized expression, restore it to preserve comment and source map emit + var parens = ts.factory.createParenthesizedExpression(node.expression); + ts.setOriginalNode(parens, node); + ts.setTextRange(parens, parseNode); + return parens; + } + return ts.factory.createParenthesizedExpression(node); + } + return node; + } + function parenthesizeExpressionForNoAsiAndDisallowedComma(node) { + return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node)); + } function emitReturnStatement(node) { emitTokenWithComment(105 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitWithStatement(node) { @@ -110020,7 +110946,7 @@ var ts; } function emitThrowStatement(node) { emitTokenWithComment(109 /* ThrowKeyword */, node.pos, writeKeyword, node); - emitExpressionWithLeadingSpace(node.expression); + emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi); writeTrailingSemicolon(); } function emitTryStatement(node) { @@ -110864,7 +111790,14 @@ var ts; } // Transformation nodes function emitPartiallyEmittedExpression(node) { + var emitFlags = ts.getEmitFlags(node); + if (!(emitFlags & 512 /* NoLeadingComments */) && node.pos !== node.expression.pos) { + emitTrailingCommentsOfPosition(node.expression.pos); + } emitExpression(node.expression); + if (!(emitFlags & 1024 /* NoTrailingComments */) && node.end !== node.expression.end) { + emitLeadingCommentsOfPosition(node.expression.end); + } } function emitCommaList(node) { emitExpressionList(node, node.elements, 528 /* CommaListElements */, /*parenthesizerRule*/ undefined); @@ -111228,10 +112161,8 @@ var ts; // Emit this child. previousSourceFileTextKind = recordBundleFileInternalSectionStart(child); if (shouldEmitInterveningComments) { - if (emitTrailingCommentsOfPosition) { - var commentRange = ts.getCommentRange(child); - emitTrailingCommentsOfPosition(commentRange.pos); - } + var commentRange = ts.getCommentRange(child); + emitTrailingCommentsOfPosition(commentRange.pos); } else { shouldEmitInterveningComments = mayEmitInterveningComments; @@ -111552,7 +112483,7 @@ var ts; function writeLineSeparatorsAndIndentBefore(node, parent) { var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */); if (leadingNewlines) { - writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false); + writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false); } return !!leadingNewlines; } @@ -113695,6 +114626,100 @@ var ts; } } ts.getImpliedNodeFormatForFile = getImpliedNodeFormatForFile; + /** @internal */ + ts.plainJSErrors = new ts.Set([ + // binder errors + ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0.code, + ts.Diagnostics.A_module_cannot_have_multiple_default_exports.code, + ts.Diagnostics.Another_export_default_is_here.code, + ts.Diagnostics.The_first_export_default_is_here.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode.code, + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here.code, + ts.Diagnostics.constructor_is_a_reserved_word.code, + ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode.code, + ts.Diagnostics.Code_contained_in_a_class_is_evaluated_in_JavaScript_s_strict_mode_which_does_not_allow_this_use_of_0_For_more_information_see_https_Colon_Slash_Slashdeveloper_mozilla_org_Slashen_US_Slashdocs_SlashWeb_SlashJavaScript_SlashReference_SlashStrict_mode.code, + ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode.code, + ts.Diagnostics.Invalid_use_of_0_in_strict_mode.code, + ts.Diagnostics.A_label_is_not_allowed_here.code, + ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode.code, + ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode.code, + // grammar errors + ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code, + ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code, + ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code, + ts.Diagnostics.A_class_member_cannot_have_the_0_keyword.code, + ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code, + ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code, + ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code, + ts.Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code, + ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code, + ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer.code, + ts.Diagnostics.A_get_accessor_cannot_have_parameters.code, + ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code, + ts.Diagnostics.A_rest_element_cannot_have_a_property_name.code, + ts.Diagnostics.A_rest_element_cannot_have_an_initializer.code, + ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code, + ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer.code, + ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code, + ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code, + ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body.code, + ts.Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code, + ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter.code, + ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code, + ts.Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + ts.Diagnostics.An_export_declaration_cannot_have_modifiers.code, + ts.Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code, + ts.Diagnostics.An_import_declaration_cannot_have_modifiers.code, + ts.Diagnostics.An_object_member_cannot_be_declared_optional.code, + ts.Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code, + ts.Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code, + ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code, + ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code, + ts.Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code, + ts.Diagnostics.Classes_can_only_extend_a_single_class.code, + ts.Diagnostics.Classes_may_not_have_a_field_named_constructor.code, + ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code, + ts.Diagnostics.Duplicate_label_0.code, + ts.Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code, + ts.Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code, + ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code, + ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code, + ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code, + ts.Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code, + ts.Diagnostics.Jump_target_cannot_cross_function_boundary.code, + ts.Diagnostics.Line_terminator_not_permitted_before_arrow.code, + ts.Diagnostics.Modifiers_cannot_appear_here.code, + ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code, + ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code, + ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code, + ts.Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, + ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code, + ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code, + ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code, + ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code, + ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code, + ts.Diagnostics.Trailing_comma_not_allowed.code, + ts.Diagnostics.Variable_declaration_list_cannot_be_empty.code, + ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code, + ts.Diagnostics._0_expected.code, + ts.Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code, + ts.Diagnostics._0_list_cannot_be_empty.code, + ts.Diagnostics._0_modifier_already_seen.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code, + ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter.code, + ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code, + ts.Diagnostics._0_modifier_cannot_be_used_here.code, + ts.Diagnostics._0_modifier_must_precede_1_modifier.code, + ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code, + ts.Diagnostics.const_declarations_must_be_initialized.code, + ts.Diagnostics.extends_clause_already_seen.code, + ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code, + ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code, + ]); /** * Determine if source file needs to be re-created even if its text hasn't changed */ @@ -114355,6 +115380,7 @@ var ts; newSourceFile.originalFileName = oldSourceFile.originalFileName; newSourceFile.resolvedPath = oldSourceFile.resolvedPath; newSourceFile.fileName = oldSourceFile.fileName; + newSourceFile.impliedNodeFormat = oldSourceFile.impliedNodeFormat; var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path); if (packageName !== undefined) { // If there are 2 different source files for the same package name and at least one of them changes, @@ -114711,14 +115737,24 @@ var ts; } var typeChecker = getDiagnosticsProducingTypeChecker(); ts.Debug.assert(!!sourceFile.bindDiagnostics); - var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options); + var isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + var isCheckJs = isJs && ts.isCheckJsEnabledForFile(sourceFile, options); + var isPlainJs = ts.isPlainJsFile(sourceFile, options.checkJs); var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false; - // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins) + // By default, only type-check .ts, .tsx, Deferred, plain JS, checked JS and External + // - plain JS: .js files with no // ts-check and checkJs: undefined + // - check JS: .js files with either // ts-check or checkJs: true + // - external: files that are added by plugins var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ - || sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); + || sourceFile.scriptKind === 5 /* External */ || isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray; var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray; - return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); + if (isPlainJs) { + bindDiagnostics = ts.filter(bindDiagnostics, function (d) { return ts.plainJSErrors.has(d.code); }); + checkDiagnostics = ts.filter(checkDiagnostics, function (d) { return ts.plainJSErrors.has(d.code); }); + } + // skip ts-expect-error errors in plain JS files, and skip JSDoc errors except in checked JS + return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined); }); } function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) { @@ -115362,14 +116398,14 @@ var ts; redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, redirectedPath); addFileIncludeReason(dupFile, reason); - sourceFileToPackageName.set(path, packageId.name); + sourceFileToPackageName.set(path, ts.packageIdToPackageName(packageId)); processingOtherFiles.push(dupFile); return dupFile; } else if (file) { // This is the first source file to have this packageId. packageIdToSourceFile.set(packageIdKey, file); - sourceFileToPackageName.set(path, packageId.name); + sourceFileToPackageName.set(path, ts.packageIdToPackageName(packageId)); } } addFileToFilesByName(file, path, redirectedPath); @@ -115732,7 +116768,7 @@ var ts; return resolvedRef; } function verifyCompilerOptions() { - var isNightly = ts.stringContains(ts.version, "-dev"); + var isNightly = ts.stringContains(ts.version, "-dev") || ts.stringContains(ts.version, "-insiders"); if (!isNightly) { if (ts.getEmitModuleKind(options) === ts.ModuleKind.Node12) { createOptionValueDiagnostic("module", ts.Diagnostics.Compiler_option_0_of_value_1_is_unstable_Use_nightly_TypeScript_to_silence_this_error_Try_updating_with_npm_install_D_typescript_next, "module", "node12"); @@ -118627,7 +119663,7 @@ var ts; function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { if (resolution.refCount) { resolution.refCount++; - ts.Debug.assertDefined(resolution.files); + ts.Debug.assertIsDefined(resolution.files); } else { resolution.refCount = 1; @@ -118695,7 +119731,7 @@ var ts; } } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { - ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath); + ts.unorderedRemoveItem(ts.Debug.checkDefined(resolution.files), filePath); resolution.refCount--; if (resolution.refCount) { return; @@ -118787,7 +119823,7 @@ var ts; if (resolution.isInvalidated || !canInvalidate(resolution)) continue; resolution.isInvalidated = invalidated = true; - for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) { + for (var _a = 0, _b = ts.Debug.checkDefined(resolution.files); _a < _b.length; _a++) { var containingFilePath = _b[_a]; (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath); // When its a file with inferred types resolution, invalidate type reference directive resolution @@ -118995,11 +120031,12 @@ var ts; }; } function isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) { + var _a; if (ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.Node12 && ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeNext) { return false; } - return ts.getImpliedNodeFormatForFile(importingSourceFileName, /*packageJsonInfoCache*/ undefined, getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS; + return ts.getImpliedNodeFormatForFile(importingSourceFileName, (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host), getModuleResolutionHost(host), compilerOptions) !== ts.ModuleKind.CommonJS; } function getModuleResolutionHost(host) { var _a; @@ -119012,28 +120049,37 @@ var ts; useCaseSensitiveFileNames: (_a = host.useCaseSensitiveFileNames) === null || _a === void 0 ? void 0 : _a.call(host), }; } - function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) { - var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {}); + // `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`? + // Because when this is called by the file renamer, `importingSourceFile` is the file being renamed, + // while `importingSourceFileName` its *new* name. We need a source file just to get its + // `impliedNodeFormat` and to detect certain preferences from existing import module specifiers. + function updateModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, oldImportSpecifier) { + var res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {}); if (res === oldImportSpecifier) return undefined; return res; } moduleSpecifiers_1.updateModuleSpecifier = updateModuleSpecifier; - // Note: importingSourceFile is just for usesJsExtensionOnImports + // `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`? + // Because when this is called by the declaration emitter, `importingSourceFile` is the implementation + // file, but `importingSourceFileName` and `toFileName` refer to declaration files (the former to the + // one currently being produced; the latter to the one being imported). We need an implementation file + // just to get its `impliedNodeFormat` and to detect certain preferences from existing import module + // specifiers. function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host) { - return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}); + return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}); } moduleSpecifiers_1.getModuleSpecifier = getModuleSpecifier; - function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host, preferences) { - var info = getInfo(importingSourceFileName, host); - var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host, preferences); - return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); }); + function getNodeModulesPackageName(compilerOptions, importingSourceFile, nodeModulesFileName, host, preferences) { + var info = getInfo(importingSourceFile.path, host); + var modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences); + return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, /*packageNameOnly*/ true); }); } moduleSpecifiers_1.getNodeModulesPackageName = getNodeModulesPackageName; - function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences, userPreferences) { + function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences, userPreferences) { var info = getInfo(importingSourceFileName, host); var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences); - return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) || + return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions); }) || getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences) { @@ -119100,7 +120146,7 @@ var ts; var relativeSpecifiers; for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) { var modulePath = modulePaths_1[_i]; - var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); + var specifier = tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions); nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier); if (specifier && modulePath.isRedirect) { // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar", @@ -119492,13 +120538,13 @@ var ts; ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions) : ts.removeFileExtension(relativePath); } - function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) { + function tryGetModuleNameAsNodeModule(_a, _b, importingSourceFile, host, options, packageNameOnly) { var path = _a.path, isRedirect = _a.isRedirect; var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory; if (!host.fileExists || !host.readFile) { return undefined; } - var parts = getNodeModulePathParts(path); + var parts = ts.getNodeModulePathParts(path); if (!parts) { return undefined; } @@ -119550,16 +120596,26 @@ var ts; // For classic resolution, only allow importing from node_modules/@types, not other node_modules return ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Classic && packageName === nodeModulesDirectoryName ? undefined : packageName; function tryDirectoryWithPackageJson(packageRootIndex) { + var _a, _b; var packageRootPath = path.substring(0, packageRootIndex); var packageJsonPath = ts.combinePaths(packageRootPath, "package.json"); var moduleFileToTry = path; - if (host.fileExists(packageJsonPath)) { - var packageJsonContent = JSON.parse(host.readFile(packageJsonPath)); - // TODO: Inject `require` or `import` condition based on the intended import mode + var cachedPackageJson = (_b = (_a = host.getPackageJsonInfoCache) === null || _a === void 0 ? void 0 : _a.call(host)) === null || _b === void 0 ? void 0 : _b.getPackageJsonInfo(packageJsonPath); + if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) { + var packageJsonContent = (cachedPackageJson === null || cachedPackageJson === void 0 ? void 0 : cachedPackageJson.packageJsonContent) || JSON.parse(host.readFile(packageJsonPath)); if (ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.Node12 || ts.getEmitModuleResolutionKind(options) === ts.ModuleResolutionKind.NodeNext) { - var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" ? tryGetModuleNameFromExports(options, path, packageRootPath, packageJsonContent.name, packageJsonContent.exports, ["node", "types"]) : undefined; + // `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate + // an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is + // usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex` + // with, so for now we just stick with the mode of the file. + var conditions = ["node", importingSourceFile.impliedNodeFormat === ts.ModuleKind.ESNext ? "import" : "require", "types"]; + var fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string" + ? tryGetModuleNameFromExports(options, path, packageRootPath, ts.getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions) + : undefined; if (fromExports) { - var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) ? fromExports : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; + var withJsExtension = !ts.hasTSFileExtension(fromExports.moduleFileToTry) + ? fromExports + : { moduleFileToTry: ts.removeFileExtension(fromExports.moduleFileToTry) + tryGetJSExtensionForFile(fromExports.moduleFileToTry, options) }; return __assign(__assign({}, withJsExtension), { verbatimFromExports: true }); } if (packageJsonContent.exports) { @@ -119611,62 +120667,10 @@ var ts; } } } - function getNodeModulePathParts(fullPath) { - // If fullPath can't be valid module file within node_modules, returns undefined. - // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js - // Returns indices: ^ ^ ^ ^ - var topLevelNodeModulesIndex = 0; - var topLevelPackageNameIndex = 0; - var packageRootIndex = 0; - var fileNameIndex = 0; - var States; - (function (States) { - States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules"; - States[States["NodeModules"] = 1] = "NodeModules"; - States[States["Scope"] = 2] = "Scope"; - States[States["PackageContent"] = 3] = "PackageContent"; - })(States || (States = {})); - var partStart = 0; - var partEnd = 0; - var state = 0 /* BeforeNodeModules */; - while (partEnd >= 0) { - partStart = partEnd; - partEnd = fullPath.indexOf("/", partStart + 1); - switch (state) { - case 0 /* BeforeNodeModules */: - if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { - topLevelNodeModulesIndex = partStart; - topLevelPackageNameIndex = partEnd; - state = 1 /* NodeModules */; - } - break; - case 1 /* NodeModules */: - case 2 /* Scope */: - if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") { - state = 2 /* Scope */; - } - else { - packageRootIndex = partEnd; - state = 3 /* PackageContent */; - } - break; - case 3 /* PackageContent */: - if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) { - state = 1 /* NodeModules */; - } - else { - state = 3 /* PackageContent */; - } - break; - } - } - fileNameIndex = partStart; - return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; - } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return ts.firstDefined(rootDirs, function (rootDir) { - var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217 - return isPathRelativeToParent(relativePath) ? undefined : relativePath; + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath; }); } function removeExtensionAndIndexPostFix(fileName, ending, options) { @@ -119733,7 +120737,7 @@ var ts; getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) } : undefined; /** - * Create a function that reports error by writing to the system and handles the formating of the diagnostic + * Create a function that reports error by writing to the system and handles the formatting of the diagnostic */ function createDiagnosticReporter(system, pretty) { var host = system === ts.sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : { @@ -119785,7 +120789,7 @@ var ts; } ts.getLocaleTimeString = getLocaleTimeString; /** - * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + * Create a function that reports watch status by writing to the system and handles the formatting of the diagnostic */ function createWatchStatusReporter(system, pretty) { return pretty ? @@ -119819,19 +120823,84 @@ var ts; return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }); } ts.getErrorCountForSummary = getErrorCountForSummary; + function getFilesInErrorForSummary(diagnostics) { + var filesInError = ts.filter(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; }) + .map(function (errorDiagnostic) { + if (errorDiagnostic.file === undefined) + return; + return "".concat(errorDiagnostic.file.fileName); + }); + return filesInError.map(function (fileName) { + var diagnosticForFileName = ts.find(diagnostics, function (diagnostic) { + return diagnostic.file !== undefined && diagnostic.file.fileName === fileName; + }); + if (diagnosticForFileName !== undefined) { + var line = ts.getLineAndCharacterOfPosition(diagnosticForFileName.file, diagnosticForFileName.start).line; + return { + fileName: fileName, + line: line + 1, + }; + } + }); + } + ts.getFilesInErrorForSummary = getFilesInErrorForSummary; function getWatchErrorSummaryDiagnosticMessage(errorCount) { return errorCount === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : ts.Diagnostics.Found_0_errors_Watching_for_file_changes; } ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage; - function getErrorSummaryText(errorCount, newLine) { + function prettyPathForFileError(error, cwd) { + var line = ts.formatColorAndReset(":" + error.line, ts.ForegroundColorEscapeSequences.Grey); + if (ts.pathIsAbsolute(error.fileName) && ts.pathIsAbsolute(cwd)) { + return ts.getRelativePathFromDirectory(cwd, error.fileName, /* ignoreCase */ false) + line; + } + return error.fileName + line; + } + function getErrorSummaryText(errorCount, filesInError, newLine, host) { if (errorCount === 0) return ""; - var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount); - return "".concat(newLine).concat(ts.flattenDiagnosticMessageText(d.messageText, newLine)).concat(newLine).concat(newLine); + var nonNilFiles = filesInError.filter(function (fileInError) { return fileInError !== undefined; }); + var distinctFileNamesWithLines = nonNilFiles.map(function (fileInError) { return "".concat(fileInError.fileName, ":").concat(fileInError.line); }) + .filter(function (value, index, self) { return self.indexOf(value) === index; }); + var firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); + var d = errorCount === 1 ? + ts.createCompilerDiagnostic(filesInError[0] !== undefined ? + ts.Diagnostics.Found_1_error_in_1 : + ts.Diagnostics.Found_1_error, errorCount, firstFileReference) : + ts.createCompilerDiagnostic(distinctFileNamesWithLines.length === 0 ? + ts.Diagnostics.Found_0_errors : + distinctFileNamesWithLines.length === 1 ? + ts.Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1 : + ts.Diagnostics.Found_0_errors_in_1_files, errorCount, distinctFileNamesWithLines.length === 1 ? firstFileReference : distinctFileNamesWithLines.length); + var suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : ""; + return "".concat(newLine).concat(ts.flattenDiagnosticMessageText(d.messageText, newLine)).concat(newLine).concat(newLine).concat(suffix); } ts.getErrorSummaryText = getErrorSummaryText; + function createTabularErrorsDisplay(filesInError, host) { + var distinctFiles = filesInError.filter(function (value, index, self) { return index === self.findIndex(function (file) { return (file === null || file === void 0 ? void 0 : file.fileName) === (value === null || value === void 0 ? void 0 : value.fileName); }); }); + if (distinctFiles.length === 0) + return ""; + var numberLength = function (num) { return Math.log(num) * Math.LOG10E + 1; }; + var fileToErrorCount = distinctFiles.map(function (file) { return [file, ts.countWhere(filesInError, function (fileInError) { return fileInError.fileName === file.fileName; })]; }); + var maxErrors = fileToErrorCount.reduce(function (acc, value) { return Math.max(acc, value[1] || 0); }, 0); + var headerRow = ts.Diagnostics.Errors_Files.message; + var leftColumnHeadingLength = headerRow.split(" ")[0].length; + var leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors)); + var headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0); + var tabularData = ""; + tabularData += " ".repeat(headerPadding) + headerRow + "\n"; + fileToErrorCount.forEach(function (row) { + var file = row[0], errorCount = row[1]; + var errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0; + var leftPadding = errorCountDigitsLength < leftPaddingGoal ? + " ".repeat(leftPaddingGoal - errorCountDigitsLength) + : ""; + var fileRef = prettyPathForFileError(file, host.getCurrentDirectory()); + tabularData += "".concat(leftPadding).concat(errorCount, " ").concat(fileRef, "\n"); + }); + return tabularData; + } function isBuilderProgram(program) { return !!program.getState; } @@ -120035,7 +121104,7 @@ var ts; listFiles(program, write); } if (reportSummary) { - reportSummary(getErrorCountForSummary(diagnostics)); + reportSummary(getErrorCountForSummary(diagnostics), getFilesInErrorForSummary(diagnostics)); } return { emitResult: emitResult, @@ -120246,7 +121315,7 @@ var ts; var system = input.system || ts.sys; var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system)); var builderProgram = ts.createIncrementalProgram(input); - var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + var exitStatus = emitFilesAndReportErrorsAndGetExitStatus(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount, filesInError) { return system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)); } : undefined); if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); return exitStatus; @@ -120329,6 +121398,7 @@ var ts; var sharedExtendedConfigFileWatchers; // Map of file watchers for extended files, shared between different referenced projects var extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation var changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution + var reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info var missingFilePathsRequestedForRelease; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations @@ -120491,14 +121561,21 @@ var ts; var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution); if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } else { + if (reportFileChangeDetectedOnCreateProgram) { + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + } createNewProgram(hasInvalidatedResolution); } changesAffectResolution = false; // reset for next sync + reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { host.afterProgramCreate(builderProgram); } @@ -120700,7 +121777,7 @@ var ts; } function updateProgramWithWatchStatus() { timerToUpdateProgram = undefined; - reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + reportFileChangeDetectedOnCreateProgram = true; updateProgram(); } function updateProgram() { @@ -122465,11 +123542,14 @@ var ts; var canReportSummary = state.watch || !!state.host.reportErrorSummary; var diagnostics = state.diagnostics; var totalErrors = 0; + var filesInError = []; if (isCircularBuildOrder(buildOrder)) { reportBuildQueue(state, buildOrder.buildOrder); reportErrors(state, buildOrder.circularDiagnostics); if (canReportSummary) totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics); + if (canReportSummary) + filesInError = __spreadArray(__spreadArray([], filesInError, true), ts.getFilesInErrorForSummary(buildOrder.circularDiagnostics), true); } else { // Report errors from the other projects @@ -122481,12 +123561,14 @@ var ts; }); if (canReportSummary) diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); }); + if (canReportSummary) + diagnostics.forEach(function (singleProjectErrors) { return __spreadArray(__spreadArray([], filesInError, true), ts.getFilesInErrorForSummary(singleProjectErrors), true); }); } if (state.watch) { reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); } else if (state.host.reportErrorSummary) { - state.host.reportErrorSummary(totalErrors); + state.host.reportErrorSummary(totalErrors, filesInError); } } /** @@ -122715,14 +123797,8 @@ var ts; var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath)); possibleSearchDirs.add(projectRootPath); possibleSearchDirs.forEach(function (searchDir) { - var packageJsonPath = ts.combinePaths(searchDir, "package.json"); - getTypingNamesFromJson(packageJsonPath, filesToWatch); - var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); - getTypingNamesFromJson(bowerJsonPath, filesToWatch); - var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components"); - getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch); - var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); - getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch); + getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch); + getTypingNames(searchDir, "package.json", "node_modules", filesToWatch); }); if (!typeAcquisition.disableFilenameBasedTypeAcquisition) { getTypingNamesFromSourceFileNames(fileNames); @@ -122771,16 +123847,100 @@ var ts; ts.forEach(typingNames, addInferredTyping); } /** - * Get the typing info from common package manager json files like package.json or bower.json + * Adds inferred typings from manifest/module pairs (think package.json + node_modules) + * + * @param projectRootPath is the path to the directory where to look for package.json, bower.json and other typing information + * @param manifestName is the name of the manifest (package.json or bower.json) + * @param modulesDirName is the directory name for modules (node_modules or bower_components). Should be lowercase! + * @param filesToWatch are the files to watch for changes. We will push things into this array. */ - function getTypingNamesFromJson(jsonPath, filesToWatch) { - if (!host.fileExists(jsonPath)) { + function getTypingNames(projectRootPath, manifestName, modulesDirName, filesToWatch) { + // First, we check the manifests themselves. They're not + // _required_, but they allow us to do some filtering when dealing + // with big flat dep directories. + var manifestPath = ts.combinePaths(projectRootPath, manifestName); + var manifest; + var manifestTypingNames; + if (host.fileExists(manifestPath)) { + filesToWatch.push(manifestPath); + manifest = ts.readConfigFile(manifestPath, function (path) { return host.readFile(path); }).config; + manifestTypingNames = ts.flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], ts.getOwnKeys); + addInferredTypings(manifestTypingNames, "Typing names in '".concat(manifestPath, "' dependencies")); + } + // Now we scan the directories for typing information in + // already-installed dependencies (if present). Note that this + // step happens regardless of whether a manifest was present, + // which is certainly a valid configuration, if an unusual one. + var packagesFolderPath = ts.combinePaths(projectRootPath, modulesDirName); + filesToWatch.push(packagesFolderPath); + if (!host.directoryExists(packagesFolderPath)) { return; } - filesToWatch.push(jsonPath); - var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config; - var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys); - addInferredTypings(jsonTypingNames, "Typing names in '".concat(jsonPath, "' dependencies")); + // There's two cases we have to take into account here: + // 1. If manifest is undefined, then we're not using a manifest. + // That means that we should scan _all_ dependencies at the top + // level of the modulesDir. + // 2. If manifest is defined, then we can do some special + // filtering to reduce the amount of scanning we need to do. + // + // Previous versions of this algorithm checked for a `_requiredBy` + // field in the package.json, but that field is only present in + // `npm@>=3 <7`. + // Package names that do **not** provide their own typings, so + // we'll look them up. + var packageNames = []; + var dependencyManifestNames = manifestTypingNames + // This is #1 described above. + ? manifestTypingNames.map(function (typingName) { return ts.combinePaths(packagesFolderPath, typingName, manifestName); }) + // And #2. Depth = 3 because scoped packages look like `node_modules/@foo/bar/package.json` + : host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 3) + .filter(function (manifestPath) { + if (ts.getBaseFileName(manifestPath) !== manifestName) { + return false; + } + // It's ok to treat + // `node_modules/@foo/bar/package.json` as a manifest, + // but not `node_modules/jquery/nested/package.json`. + // We only assume depth 3 is ok for formally scoped + // packages. So that needs this dance here. + var pathComponents = ts.getPathComponents(ts.normalizePath(manifestPath)); + var isScoped = pathComponents[pathComponents.length - 3][0] === "@"; + return isScoped && pathComponents[pathComponents.length - 4].toLowerCase() === modulesDirName || // `node_modules/@foo/bar` + !isScoped && pathComponents[pathComponents.length - 3].toLowerCase() === modulesDirName; // `node_modules/foo` + }); + if (log) + log("Searching for typing names in ".concat(packagesFolderPath, "; all files: ").concat(JSON.stringify(dependencyManifestNames))); + // Once we have the names of things to look up, we iterate over + // and either collect their included typings, or add them to the + // list of typings we need to look up separately. + for (var _i = 0, dependencyManifestNames_1 = dependencyManifestNames; _i < dependencyManifestNames_1.length; _i++) { + var manifestPath_1 = dependencyManifestNames_1[_i]; + var normalizedFileName = ts.normalizePath(manifestPath_1); + var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var manifest_1 = result_1.config; + // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used + // to download d.ts files from DefinitelyTyped + if (!manifest_1.name) { + continue; + } + var ownTypes = manifest_1.types || manifest_1.typings; + if (ownTypes) { + var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); + if (host.fileExists(absolutePath)) { + if (log) + log(" Package '".concat(manifest_1.name, "' provides its own types.")); + inferredTypings.set(manifest_1.name, absolutePath); + } + else { + if (log) + log(" Package '".concat(manifest_1.name, "' provides its own types but they are missing.")); + } + } + else { + packageNames.push(manifest_1.name); + } + } + addInferredTypings(packageNames, " Found package names"); } /** * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js" @@ -122806,55 +123966,6 @@ var ts; addInferredTyping("react"); } } - /** - * Infer typing names from packages folder (ex: node_module, bower_components) - * @param packagesFolderPath is the path to the packages folder - */ - function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) { - filesToWatch.push(packagesFolderPath); - // Todo: add support for ModuleResolutionHost too - if (!host.directoryExists(packagesFolderPath)) { - return; - } - // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar` - var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); - if (log) - log("Searching for typing names in ".concat(packagesFolderPath, "; all files: ").concat(JSON.stringify(fileNames))); - var packageNames = []; - for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) { - var fileName = fileNames_1[_i]; - var normalizedFileName = ts.normalizePath(fileName); - var baseFileName = ts.getBaseFileName(normalizedFileName); - if (baseFileName !== "package.json" && baseFileName !== "bower.json") { - continue; - } - var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_1.config; - // npm 3's package.json contains a "_requiredBy" field - // we should include all the top level module names for npm 2, and only module names whose - // "_requiredBy" field starts with "#" or equals "/" for npm 3. - if (baseFileName === "package.json" && packageJson._requiredBy && - ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { - continue; - } - // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used - // to download d.ts files from DefinitelyTyped - if (!packageJson.name) { - continue; - } - var ownTypes = packageJson.types || packageJson.typings; - if (ownTypes) { - var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName)); - if (log) - log(" Package '".concat(packageJson.name, "' provides its own types.")); - inferredTypings.set(packageJson.name, absolutePath); - } - else { - packageNames.push(packageJson.name); - } - } - addInferredTypings(packageNames, " Found package names"); - } } JsTyping.discoverTypings = discoverTypings; var NameValidationResult; @@ -123190,6 +124301,7 @@ var ts; ScriptElementKind["externalModuleName"] = "external module name"; /** * <JsxTagName attribute1 attribute2={0} /> + * @deprecated */ ScriptElementKind["jsxAttribute"] = "JSX attribute"; /** String literal */ @@ -123365,13 +124477,6 @@ var ts; || ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isImportEqualsDeclaration(parent) && node === parent.name) { - var decl = parent; - while (decl) { - if (ts.isImportEqualsDeclaration(decl) || ts.isImportClause(decl) || ts.isExportDeclaration(decl)) { - return decl.isTypeOnly ? 2 /* Type */ : 7 /* All */; - } - decl = decl.parent; - } return 7 /* All */; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { @@ -124522,7 +125627,7 @@ var ts; isWhiteSpaceOnlyJsxText(child); if (lookInPreviousChild) { // actual start of the node is past the position - previous token should be at the end of previous child - var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile); + var candidate_1 = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ i, sourceFile, n.kind); return candidate_1 && findRightmostToken(candidate_1, sourceFile); } else { @@ -124536,7 +125641,7 @@ var ts; // the only known case is when position is at the end of the file. // Try to find the rightmost token in the file without filtering. // Namely we are skipping the check: 'position < node.end' - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } } @@ -124552,17 +125657,19 @@ var ts; if (children.length === 0) { return n; } - var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile); + var candidate = findRightmostChildNodeWithTokens(children, /*exclusiveStartPosition*/ children.length, sourceFile, n.kind); return candidate && findRightmostToken(candidate, sourceFile); } /** * Finds the rightmost child to the left of `children[exclusiveStartPosition]` which is a non-all-whitespace token or has constituent tokens. */ - function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile) { + function findRightmostChildNodeWithTokens(children, exclusiveStartPosition, sourceFile, parentKind) { for (var i = exclusiveStartPosition - 1; i >= 0; i--) { var child = children[i]; if (isWhiteSpaceOnlyJsxText(child)) { - ts.Debug.assert(i > 0, "`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + if (i === 0 && (parentKind === 11 /* JsxText */ || parentKind === 278 /* JsxSelfClosingElement */)) { + ts.Debug.fail("`JsxText` tokens should not be the first child of `JsxElement | JsxSelfClosingElement`"); + } } else if (nodeHasTokens(children[i], sourceFile)) { return children[i]; @@ -125088,6 +126195,7 @@ var ts; useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, getModuleSpecifierCache: ts.maybeBind(host, host.getModuleSpecifierCache), + getPackageJsonInfoCache: function () { var _a; return (_a = program.getModuleResolutionCache()) === null || _a === void 0 ? void 0 : _a.getPackageJsonInfoCache(); }, getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), redirectTargetsMap: program.redirectTargetsMap, getProjectReferenceRedirect: function (fileName) { return program.getProjectReferenceRedirect(fileName); }, @@ -125501,7 +126609,7 @@ var ts; parts.push(linkTextPart(text)); } else { - parts.push(linkTextPart(name + (suffix ? "" : " ") + text)); + parts.push(linkTextPart(name + (suffix || text.indexOf("://") === 0 ? "" : " ") + text)); } } parts.push(linkPart("}")); @@ -125902,7 +127010,6 @@ var ts; || kind === 165 /* PropertySignature */ || kind === 167 /* MethodSignature */; } - ts.syntaxRequiresTrailingCommaOrSemicolonOrASI = syntaxRequiresTrailingCommaOrSemicolonOrASI; function syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI(kind) { return kind === 255 /* FunctionDeclaration */ || kind === 170 /* Constructor */ @@ -125910,11 +127017,9 @@ var ts; || kind === 171 /* GetAccessor */ || kind === 172 /* SetAccessor */; } - ts.syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI = syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI; function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind) { return kind === 260 /* ModuleDeclaration */; } - ts.syntaxRequiresTrailingModuleBlockOrSemicolonOrASI = syntaxRequiresTrailingModuleBlockOrSemicolonOrASI; function syntaxRequiresTrailingSemicolonOrASI(kind) { return kind === 236 /* VariableStatement */ || kind === 237 /* ExpressionStatement */ @@ -125989,19 +127094,34 @@ var ts; ts.forEachChild(sourceFile, function visit(node) { if (syntaxRequiresTrailingSemicolonOrASI(node.kind)) { var lastToken = node.getLastToken(sourceFile); - if (lastToken && lastToken.kind === 26 /* SemicolonToken */) { + if ((lastToken === null || lastToken === void 0 ? void 0 : lastToken.kind) === 26 /* SemicolonToken */) { withSemicolon++; } else { withoutSemicolon++; } } + else if (syntaxRequiresTrailingCommaOrSemicolonOrASI(node.kind)) { + var lastToken = node.getLastToken(sourceFile); + if ((lastToken === null || lastToken === void 0 ? void 0 : lastToken.kind) === 26 /* SemicolonToken */) { + withSemicolon++; + } + else if (lastToken && lastToken.kind !== 27 /* CommaToken */) { + var lastTokenLine = ts.getLineAndCharacterOfPosition(sourceFile, lastToken.getStart(sourceFile)).line; + var nextTokenLine = ts.getLineAndCharacterOfPosition(sourceFile, ts.getSpanOfTokenAtPosition(sourceFile, lastToken.end).start).line; + // Avoid counting missing semicolon in single-line objects: + // `function f(p: { x: string /*no semicolon here is insignificant*/ }) {` + if (lastTokenLine !== nextTokenLine) { + withoutSemicolon++; + } + } + } if (withSemicolon + withoutSemicolon >= nStatementsToObserve) { return true; } return ts.forEachChild(node, visit); }); - // One statement missing a semicolon isn’t sufficient evidence to say the user + // One statement missing a semicolon isn't sufficient evidence to say the user // doesn’t want semicolons, because they may not even be done writing that statement. if (withSemicolon === 0 && withoutSemicolon <= 1) { return true; @@ -126200,7 +127320,7 @@ var ts; if (!ts.stringContains(importedFileName, "node_modules")) { return undefined; } - var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile.path, importedFileName, moduleSpecifierResolutionHost, preferences); + var specifier = ts.moduleSpecifiers.getNodeModulesPackageName(host.getCompilationSettings(), fromFile, importedFileName, moduleSpecifierResolutionHost, preferences); if (!specifier) { return undefined; } @@ -126310,15 +127430,35 @@ var ts; return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray; } ts.firstOrOnly = firstOrOnly; - function getNameForExportedSymbol(symbol, scriptTarget) { - if (!(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */)) { + function getNamesForExportedSymbol(symbol, scriptTarget) { + if (needsNameFromDeclaration(symbol)) { + var fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); + if (fromDeclaration) + return fromDeclaration; + var fileNameCase = ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ false); + var capitalized = ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, /*preferCapitalized*/ true); + if (fileNameCase === capitalized) + return fileNameCase; + return [fileNameCase, capitalized]; + } + return symbol.name; + } + ts.getNamesForExportedSymbol = getNamesForExportedSymbol; + function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) { + if (needsNameFromDeclaration(symbol)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. - return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }) - || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget); + return getDefaultLikeExportNameFromDeclaration(symbol) + || ts.codefix.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized); } return symbol.name; } ts.getNameForExportedSymbol = getNameForExportedSymbol; + function needsNameFromDeclaration(symbol) { + return !(symbol.flags & 33554432 /* Transient */) && (symbol.escapedName === "export=" /* ExportEquals */ || symbol.escapedName === "default" /* Default */); + } + function getDefaultLikeExportNameFromDeclaration(symbol) { + return ts.firstDefined(symbol.declarations, function (d) { var _a; return ts.isExportAssignment(d) ? (_a = ts.tryCast(ts.skipOuterExpressions(d.expression), ts.isIdentifier)) === null || _a === void 0 ? void 0 : _a.text : undefined; }); + } function getSymbolParentOrFail(symbol) { var _a; return ts.Debug.checkDefined(symbol.parent, "Symbol parent was undefined. Flags: ".concat(ts.Debug.formatSymbolFlags(symbol.flags), ". ") + @@ -126400,6 +127540,16 @@ var ts; : ts.getLocaleSpecificMessage(diag); } ts.diagnosticToString = diagnosticToString; + /** + * Get format code settings for a code writing context (e.g. when formatting text changes or completions code). + */ + function getFormatCodeSettingsForWriting(_a, sourceFile) { + var options = _a.options; + var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore; + var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !probablyUsesSemicolons(sourceFile); + return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore }); + } + ts.getFormatCodeSettingsForWriting = getFormatCodeSettingsForWriting; // #endregion })(ts || (ts = {})); /*@internal*/ @@ -126423,6 +127573,17 @@ var ts; var exportInfoId = 1; var exportInfo = ts.createMultiMap(); var symbols = new ts.Map(); + /** + * Key: node_modules package name (no @types). + * Value: path to deepest node_modules folder seen that is + * both visible to `usableByFileName` and contains the package. + * + * Later, we can see if a given SymbolExportInfo is shadowed by + * a another installation of the same package in a deeper + * node_modules folder by seeing if its path starts with the + * value stored here. + */ + var packages = new ts.Map(); var usableByFileName; var cache = { isUsableByFile: function (importingFile) { return importingFile === usableByFileName; }, @@ -126432,11 +127593,32 @@ var ts; symbols.clear(); usableByFileName = undefined; }, - add: function (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, scriptTarget, checker) { + add: function (importingFile, symbol, symbolTableKey, moduleSymbol, moduleFile, exportKind, isFromPackageJson, checker) { if (importingFile !== usableByFileName) { cache.clear(); usableByFileName = importingFile; } + var packageName; + if (moduleFile) { + var nodeModulesPathParts = ts.getNodeModulePathParts(moduleFile.fileName); + if (nodeModulesPathParts) { + var topLevelNodeModulesIndex = nodeModulesPathParts.topLevelNodeModulesIndex, topLevelPackageNameIndex = nodeModulesPathParts.topLevelPackageNameIndex, packageRootIndex = nodeModulesPathParts.packageRootIndex; + packageName = ts.unmangleScopedPackageName(ts.getPackageNameFromTypesPackageName(moduleFile.fileName.substring(topLevelPackageNameIndex + 1, packageRootIndex))); + if (ts.startsWith(importingFile, moduleFile.path.substring(0, topLevelNodeModulesIndex))) { + var prevDeepestNodeModulesPath = packages.get(packageName); + var nodeModulesPath = moduleFile.fileName.substring(0, topLevelPackageNameIndex); + if (prevDeepestNodeModulesPath) { + var prevDeepestNodeModulesIndex = prevDeepestNodeModulesPath.indexOf(ts.nodeModulesPathPart); + if (topLevelNodeModulesIndex > prevDeepestNodeModulesIndex) { + packages.set(packageName, nodeModulesPath); + } + } + else { + packages.set(packageName, nodeModulesPath); + } + } + } + } var isDefault = exportKind === 1 /* Default */; var namedSymbol = isDefault && ts.getLocalSymbolForExportDefault(symbol) || symbol; // 1. A named export must be imported by its key in `moduleSymbol.exports` or `moduleSymbol.members`. @@ -126446,9 +127628,11 @@ var ts; // 3. Otherwise, we have a default/namespace import that can be imported by any name, and // `symbolTableKey` will be something undesirable like `export=` or `default`, so we try to // get a better name. - var importedName = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) + var names = exportKind === 0 /* Named */ || ts.isExternalModuleSymbol(namedSymbol) ? ts.unescapeLeadingUnderscores(symbolTableKey) - : ts.getNameForExportedSymbol(namedSymbol, scriptTarget); + : ts.getNamesForExportedSymbol(namedSymbol, /*scriptTarget*/ undefined); + var symbolName = typeof names === "string" ? names : names[0]; + var capitalizedSymbolName = typeof names === "string" ? undefined : names[1]; var moduleName = ts.stripQuotes(moduleSymbol.name); var id = exportInfoId++; var target = ts.skipAlias(symbol, checker); @@ -126456,13 +127640,15 @@ var ts; var storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? undefined : moduleSymbol; if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); - exportInfo.add(key(importedName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { + exportInfo.add(key(symbolName, symbol, ts.isExternalModuleNameRelative(moduleName) ? undefined : moduleName, checker), { id: id, symbolTableKey: symbolTableKey, - symbolName: importedName, + symbolName: symbolName, + capitalizedSymbolName: capitalizedSymbolName, moduleName: moduleName, moduleFile: moduleFile, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, + packageName: packageName, exportKind: exportKind, targetFlags: target.flags, isFromPackageJson: isFromPackageJson, @@ -126476,12 +127662,19 @@ var ts; var result = exportInfo.get(key); return result === null || result === void 0 ? void 0 : result.map(rehydrateCachedInfo); }, - forEach: function (importingFile, action) { + search: function (importingFile, preferCapitalized, matches, action) { if (importingFile !== usableByFileName) return; exportInfo.forEach(function (info, key) { var _a = parseKey(key), symbolName = _a.symbolName, ambientModuleName = _a.ambientModuleName; - action(info.map(rehydrateCachedInfo), symbolName, !!ambientModuleName, key); + var name = preferCapitalized && info[0].capitalizedSymbolName || symbolName; + if (matches(name, info[0].targetFlags)) { + var rehydrated = info.map(rehydrateCachedInfo); + var filtered = rehydrated.filter(function (r, i) { return isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName); }); + if (filtered.length) { + action(filtered, name, !!ambientModuleName, key); + } + } }); }, releaseSymbols: function () { @@ -126581,6 +127774,12 @@ var ts; } return true; } + function isNotShadowedByDeeperNodeModulesPackage(info, packageName) { + if (!packageName || !info.moduleFileName) + return true; + var packageDeepestNodeModulesPath = packages.get(packageName); + return !packageDeepestNodeModulesPath || ts.startsWith(info.moduleFileName, packageDeepestNodeModulesPath); + } } ts.createCacheableExportInfoMap = createCacheableExportInfoMap; function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { @@ -126663,7 +127862,6 @@ var ts; } (_d = host.log) === null || _d === void 0 ? void 0 : _d.call(host, "getExportInfoMap: cache miss or empty; calculating new results"); var compilerOptions = program.getCompilerOptions(); - var scriptTarget = ts.getEmitScriptTarget(compilerOptions); var moduleCount = 0; forEachExternalModuleToImportFrom(program, host, /*useAutoImportProvider*/ true, function (moduleSymbol, moduleFile, program, isFromPackageJson) { if (++moduleCount % 100 === 0) @@ -126674,11 +127872,11 @@ var ts; // Note: I think we shouldn't actually see resolved module symbols here, but weird merges // can cause it to happen: see 'completionsImport_mergedReExport.ts' if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { - cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, scriptTarget, checker); + cache.add(importingFile.path, defaultInfo.symbol, defaultInfo.exportKind === 1 /* Default */ ? "default" /* Default */ : "export=" /* ExportEquals */, moduleSymbol, moduleFile, defaultInfo.exportKind, isFromPackageJson, checker); } checker.forEachExportAndPropertyOfModule(moduleSymbol, function (exported, key) { if (exported !== (defaultInfo === null || defaultInfo === void 0 ? void 0 : defaultInfo.symbol) && isImportableSymbol(exported, checker) && ts.addToSeen(seenExports, key)) { - cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, scriptTarget, checker); + cache.add(importingFile.path, exported, key, moduleSymbol, moduleFile, 0 /* Named */, isFromPackageJson, checker); } }); }); @@ -127719,6 +128917,9 @@ var ts; } return; } + if (ts.isConstTypeReference(token.parent)) { + return 3 /* keyword */; + } } return 2 /* identifier */; } @@ -128019,8 +129220,9 @@ var ts; case 0 /* Paths */: return convertPathCompletions(completion.paths); case 1 /* Properties */: { - var entries = []; - Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options); // Target will not be used, so arbitrary + var entries = ts.createSortedArray(); + Completions.getCompletionEntriesFromSymbols(completion.symbols, entries, contextToken, contextToken, sourceFile, sourceFile, host, program, 99 /* ESNext */, log, 4 /* String */, preferences, options, + /*formatContext*/ undefined); // Target will not be used, so arbitrary return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: completion.hasIndexSignature, optionalReplacementSpan: optionalReplacementSpan, entries: entries }; } case 2 /* Types */: { @@ -128217,7 +129419,7 @@ var ts; var types = ts.flatMap(candidates, function (candidate) { if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; - var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); + var type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); return getStringLiteralTypes(type, uniques); }); @@ -128748,6 +129950,8 @@ var ts; CompletionSource["ThisProperty"] = "ThisProperty/"; /** Auto-import that comes attached to a class member snippet */ CompletionSource["ClassMemberSnippet"] = "ClassMemberSnippet/"; + /** A type-only import that needs to be promoted in order to be used at the completion location */ + CompletionSource["TypeOnlyAlias"] = "TypeOnlyAlias/"; })(CompletionSource = Completions.CompletionSource || (Completions.CompletionSource = {})); var SymbolOriginInfoKind; (function (SymbolOriginInfoKind) { @@ -128757,6 +129961,7 @@ var ts; SymbolOriginInfoKind[SymbolOriginInfoKind["Promise"] = 8] = "Promise"; SymbolOriginInfoKind[SymbolOriginInfoKind["Nullable"] = 16] = "Nullable"; SymbolOriginInfoKind[SymbolOriginInfoKind["ResolvedExport"] = 32] = "ResolvedExport"; + SymbolOriginInfoKind[SymbolOriginInfoKind["TypeOnlyAlias"] = 64] = "TypeOnlyAlias"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberNoExport"] = 2] = "SymbolMemberNoExport"; SymbolOriginInfoKind[SymbolOriginInfoKind["SymbolMemberExport"] = 6] = "SymbolMemberExport"; })(SymbolOriginInfoKind || (SymbolOriginInfoKind = {})); @@ -128784,6 +129989,9 @@ var ts; function originIsNullableMember(origin) { return !!(origin.kind & 16 /* Nullable */); } + function originIsTypeOnlyAlias(origin) { + return !!(origin && origin.kind & 64 /* TypeOnlyAlias */); + } var KeywordCompletionFilters; (function (KeywordCompletionFilters) { KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; @@ -128806,6 +130014,7 @@ var ts; function resolvingModuleSpecifiers(logPrefix, host, program, sourceFile, preferences, isForImportStatementCompletion, cb) { var _a, _b, _c; var start = ts.timestamp(); + var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); var resolutionLimitExceeded = false; var ambientCount = 0; var resolvedCount = 0; @@ -128828,7 +130037,7 @@ var ts; var shouldResolveModuleSpecifier = isForImportStatementCompletion || preferences.allowIncompleteCompletions && resolvedCount < Completions.moduleSpecifierResolutionLimit; var shouldGetModuleSpecifierFromCache = !shouldResolveModuleSpecifier && preferences.allowIncompleteCompletions && cacheAttemptCount < Completions.moduleSpecifierResolutionCacheAttemptLimit; var result = (shouldResolveModuleSpecifier || shouldGetModuleSpecifierFromCache) - ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, sourceFile, program, host, preferences, shouldGetModuleSpecifierFromCache) + ? ts.codefix.getModuleSpecifierForBestExportInfo(exportInfo, sourceFile, program, host, preferences, packageJsonImportFilter, shouldGetModuleSpecifierFromCache) : undefined; if (!shouldResolveModuleSpecifier && !shouldGetModuleSpecifierFromCache || shouldGetModuleSpecifierFromCache && !result) { resolutionLimitExceeded = true; @@ -128841,7 +130050,7 @@ var ts; return result; } } - function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken) { + function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext) { var _a; var previousToken = getRelevantTokens(position, sourceFile).previousToken; if (triggerCharacter && !ts.isInString(sourceFile, position, previousToken) && !isValidTrigger(sourceFile, triggerCharacter, previousToken, position)) { @@ -128881,7 +130090,7 @@ var ts; } switch (completionData.kind) { case 0 /* Data */: - var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences); + var response = completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position); if (response === null || response === void 0 ? void 0 : response.isIncomplete) { incompleteCompletionsCache === null || incompleteCompletionsCache === void 0 ? void 0 : incompleteCompletionsCache.set(response); } @@ -128901,6 +130110,29 @@ var ts; } } Completions.getCompletionsAtPosition = getCompletionsAtPosition; + // Editors will use the `sortText` and then fall back to `name` for sorting, but leave ties in response order. + // So, it's important that we sort those ties in the order we want them displayed if it matters. We don't + // strictly need to sort by name or SortText here since clients are going to do it anyway, but we have to + // do the work of comparing them so we can sort those ties appropriately; plus, it makes the order returned + // by the language service consistent with what TS Server does and what editors typically do. This also makes + // completions tests make more sense. We used to sort only alphabetically and only in the server layer, but + // this made tests really weird, since most fourslash tests don't use the server. + function compareCompletionEntries(entryInArray, entryToInsert) { + var _a, _b; + var result = ts.compareStringsCaseSensitiveUI(entryInArray.sortText, entryToInsert.sortText); + if (result === 0 /* EqualTo */) { + result = ts.compareStringsCaseSensitiveUI(entryInArray.name, entryToInsert.name); + } + if (result === 0 /* EqualTo */ && ((_a = entryInArray.data) === null || _a === void 0 ? void 0 : _a.moduleSpecifier) && ((_b = entryToInsert.data) === null || _b === void 0 ? void 0 : _b.moduleSpecifier)) { + // Sort same-named auto-imports by module specifier + result = ts.compareNumberOfDirectorySeparators(entryInArray.data.moduleSpecifier, entryToInsert.data.moduleSpecifier); + } + if (result === 0 /* EqualTo */) { + // Fall back to symbol order - if we return `EqualTo`, `insertSorted` will put later symbols first. + return -1 /* LessThan */; + } + return result; + } function completionEntryDataIsResolved(data) { return !!(data === null || data === void 0 ? void 0 : data.moduleSpecifier); } @@ -128978,8 +130210,8 @@ var ts; // StringLiteralLike locations are handled separately in stringCompletions.ts return (location === null || location === void 0 ? void 0 : location.kind) === 79 /* Identifier */ ? ts.createTextSpanFromNode(location) : undefined; } - function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; + function completionInfoFromData(sourceFile, host, program, compilerOptions, log, completionData, preferences, formatContext, position) { + var symbols = completionData.symbols, contextToken = completionData.contextToken, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, isTypeOnlyLocation = completionData.isTypeOnlyLocation, isJsxIdentifierExpected = completionData.isJsxIdentifierExpected, isRightOfOpenTag = completionData.isRightOfOpenTag, importCompletionNode = completionData.importCompletionNode, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression, symbolToSortTextIdMap = completionData.symbolToSortTextIdMap, hasUnresolvedAutoImports = completionData.hasUnresolvedAutoImports; // Verify if the file is JSX language variant if (ts.getLanguageVariant(sourceFile.scriptKind) === 1 /* JSX */) { var completionInfo = getJsxClosingTagCompletion(location, sourceFile); @@ -128987,31 +130219,38 @@ var ts; return completionInfo; } } - var entries = []; + var entries = ts.createSortedArray(); if (isUncheckedFile(sourceFile, compilerOptions)) { var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); - getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); // TODO: GH#18217 + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag); + getJSCompletionEntries(sourceFile, location.pos, uniqueNames, ts.getEmitScriptTarget(compilerOptions), entries); } else { if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, - /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap); + /*replacementToken*/ undefined, contextToken, location, sourceFile, host, program, ts.getEmitScriptTarget(compilerOptions), log, completionKind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, isJsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag); } if (keywordFilters !== 0 /* None */) { - var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); + var entryNames_1 = new ts.Set(entries.map(function (e) { return e.name; })); for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; - if (!entryNames.has(keywordEntry.name)) { - entries.push(keywordEntry); + if (!entryNames_1.has(keywordEntry.name)) { + ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); } } } - for (var _b = 0, literals_1 = literals; _b < literals_1.length; _b++) { - var literal = literals_1[_b]; - entries.push(createCompletionEntryForLiteral(sourceFile, preferences, literal)); + var entryNames = new ts.Set(entries.map(function (e) { return e.name; })); + for (var _b = 0, _c = getContextualKeywords(contextToken, position); _b < _c.length; _b++) { + var keywordEntry = _c[_b]; + if (!entryNames.has(keywordEntry.name)) { + ts.insertSorted(entries, keywordEntry, compareCompletionEntries, /*allowDuplicates*/ true); + } + } + for (var _d = 0, literals_1 = literals; _d < literals_1.length; _d++) { + var literal = literals_1[_d]; + ts.insertSorted(entries, createCompletionEntryForLiteral(sourceFile, preferences, literal), compareCompletionEntries, /*allowDuplicates*/ true); } return { isGlobalCompletion: isInSnippetScope, @@ -129087,13 +130326,13 @@ var ts; var realName = ts.unescapeLeadingUnderscores(name); if (!uniqueNames.has(realName) && ts.isIdentifierText(realName, target)) { uniqueNames.add(realName); - entries.push({ + ts.insertSorted(entries, { name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: SortText.JavascriptIdentifiers, isFromUncheckedFile: true - }); + }, compareCompletionEntries); } }); } @@ -129104,7 +130343,7 @@ var ts; function createCompletionEntryForLiteral(sourceFile, preferences, literal) { return { name: completionNameForLiteral(sourceFile, preferences, literal), kind: "string" /* string */, kindModifiers: "" /* none */, sortText: SortText.LocationPriority }; } - function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind) { + function createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, options, preferences, completionKind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag) { var _a, _b; var insertText; var replacementSpan = ts.getReplacementSpanForContextToken(replacementToken); @@ -129164,19 +130403,21 @@ var ts; isSnippet = preferences.includeCompletionsWithSnippetText ? true : undefined; } } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) { + hasAction = true; + } if (preferences.includeCompletionsWithClassMemberSnippets && preferences.includeCompletionsWithInsertText && completionKind === 3 /* MemberLike */ && isClassLikeMemberCompletion(symbol, location)) { var importAdder = void 0; - (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); + (_b = getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext), insertText = _b.insertText, isSnippet = _b.isSnippet, importAdder = _b.importAdder); if (importAdder === null || importAdder === void 0 ? void 0 : importAdder.hasFixes()) { hasAction = true; source = CompletionSource.ClassMemberSnippet; } } - var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location); - if (kind === "JSX attribute" /* jsxAttribute */ && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { + if (isJsxIdentifierExpected && !isRightOfOpenTag && preferences.includeCompletionsWithSnippetText && preferences.jsxAttributeCompletionStyle && preferences.jsxAttributeCompletionStyle !== "none") { var useBraces_1 = preferences.jsxAttributeCompletionStyle === "braces"; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, location); // If is boolean like or undefined, don't return a snippet we want just to return the completion. @@ -129214,7 +130455,7 @@ var ts; // entries (like JavaScript identifier entries). return { name: name, - kind: kind, + kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(typeChecker, symbol), sortText: sortText, source: source, @@ -129268,7 +130509,7 @@ var ts; ts.isSyntaxList(location) && ts.isClassLike(location.parent))); } - function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken) { + function getEntryForMemberCompletion(host, program, options, preferences, name, symbol, location, contextToken, formatContext) { var classLikeDeclaration = ts.findAncestor(location, ts.isClassLike); if (!classLikeDeclaration) { return { insertText: name }; @@ -129285,15 +130526,16 @@ var ts; newLine: ts.getNewLineKind(ts.getNewLineCharacter(options, ts.maybeBind(host, host.getNewLine))), }); var importAdder = ts.codefix.createImportAdder(sourceFile, program, preferences, host); + // Create empty body for possible method implementation. var body; if (preferences.includeCompletionsWithSnippetText) { isSnippet = true; // We are adding a tabstop (i.e. `$0`) in the body of the suggested member, // if it has one, so that the cursor ends up in the body once the completion is inserted. // Note: this assumes we won't have more than one body in the completion nodes, which should be the case. - var emptyStatement = ts.factory.createExpressionStatement(ts.factory.createIdentifier("")); - ts.setSnippetElement(emptyStatement, { kind: 0 /* TabStop */, order: 0 }); - body = ts.factory.createBlock([emptyStatement], /* multiline */ true); + var emptyStmt = ts.factory.createEmptyStatement(); + body = ts.factory.createBlock([emptyStmt], /* multiline */ true); + ts.setSnippetElement(emptyStmt, { kind: 0 /* TabStop */, order: 0 }); } else { body = ts.factory.createBlock([], /* multiline */ true); @@ -129339,7 +130581,27 @@ var ts; completionNodes.push(node); }, body, 2 /* Property */, isAbstract); if (completionNodes.length) { - insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + // If we have access to formatting settings, we print the nodes using the emitter, + // and then format the printed text. + if (formatContext) { + var syntheticFile_1 = { + text: printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile), + getLineAndCharacterOfPosition: function (pos) { + return ts.getLineAndCharacterOfPosition(this, pos); + }, + }; + var formatOptions_1 = ts.getFormatCodeSettingsForWriting(formatContext, sourceFile); + var changes = ts.flatMap(completionNodes, function (node) { + var nodeWithPos = ts.textChanges.assignPositionsToNode(node); + return ts.formatting.formatNodeGivenIndentation(nodeWithPos, syntheticFile_1, sourceFile.languageVariant, + /* indentation */ 0, + /* delta */ 0, __assign(__assign({}, formatContext), { options: formatOptions_1 })); + }); + insertText = ts.textChanges.applyChanges(syntheticFile_1.text, changes); + } + else { // Otherwise, just use emitter to print the new nodes. + insertText = printer.printSnippetList(1 /* MultiLine */ | 131072 /* NoTrailingNewLine */, ts.factory.createNodeArray(completionNodes), sourceFile); + } } return { insertText: insertText, isSnippet: isSnippet, importAdder: importAdder }; } @@ -129383,8 +130645,8 @@ var ts; return undefined; } function createSnippetPrinter(printerOptions) { - var printer = ts.createPrinter(printerOptions); - var baseWriter = ts.createTextWriter(ts.getNewLineCharacter(printerOptions)); + var baseWriter = ts.textChanges.createWriter(ts.getNewLineCharacter(printerOptions)); + var printer = ts.createPrinter(printerOptions, baseWriter); var writer = __assign(__assign({}, baseWriter), { write: function (s) { return baseWriter.write(ts.escapeSnippetText(s)); }, nonEscapingWrite: baseWriter.write, writeLiteral: function (s) { return baseWriter.writeLiteral(ts.escapeSnippetText(s)); }, writeStringLiteral: function (s) { return baseWriter.writeStringLiteral(ts.escapeSnippetText(s)); }, writeSymbol: function (s, symbol) { return baseWriter.writeSymbol(ts.escapeSnippetText(s), symbol); }, writeParameter: function (s) { return baseWriter.writeParameter(ts.escapeSnippetText(s)); }, writeComment: function (s) { return baseWriter.writeComment(ts.escapeSnippetText(s)); }, writeProperty: function (s) { return baseWriter.writeProperty(ts.escapeSnippetText(s)); } }); return { printSnippetList: printSnippetList, @@ -129488,8 +130750,11 @@ var ts; if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 1 /* ThisType */) { return CompletionSource.ThisProperty; } + if ((origin === null || origin === void 0 ? void 0 : origin.kind) === 64 /* TypeOnlyAlias */) { + return CompletionSource.TypeOnlyAlias; + } } - function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap) { + function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importCompletionNode, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextIdMap, isJsxIdentifierExpected, isRightOfOpenTag) { var _a; var start = ts.timestamp(); var variableDeclaration = getVariableDeclaration(location); @@ -129510,14 +130775,14 @@ var ts; var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; var sortTextId = (_a = symbolToSortTextIdMap === null || symbolToSortTextIdMap === void 0 ? void 0 : symbolToSortTextIdMap[ts.getSymbolId(symbol)]) !== null && _a !== void 0 ? _a : 11 /* LocationPriority */; var sortText = (isDeprecated(symbol, typeChecker) ? 8 /* DeprecatedOffset */ + sortTextId : sortTextId).toString(); - var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind); + var entry = createCompletionEntry(symbol, sortText, replacementToken, contextToken, location, sourceFile, host, program, name, needsConvertPropertyAccess, origin, recommendedCompletion, propertyAccessToConvert, isJsxInitializer, importCompletionNode, useSemicolons, compilerOptions, preferences, kind, formatContext, isJsxIdentifierExpected, isRightOfOpenTag); if (!entry) { continue; } /** True for locals; false for globals, module exports from other files, `this.` completions. */ - var shouldShadowLaterSymbols = !origin && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); + var shouldShadowLaterSymbols = (!origin || originIsTypeOnlyAlias(origin)) && !(symbol.parent === undefined && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === location.getSourceFile(); })); uniques.set(name, shouldShadowLaterSymbols); - entries.push(entry); + ts.insertSorted(entries, entry, compareCompletionEntries, /*allowDuplicates*/ true); } log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (ts.timestamp() - start)); // Prevent consumers of this map from having to worry about @@ -129528,6 +130793,7 @@ var ts; add: function (name) { return uniques.set(name, true); }, }; function shouldIncludeSymbol(symbol, symbolToSortTextIdMap) { + var allFlags = symbol.flags; if (!ts.isSourceFile(location)) { // export = /**/ here we want to get all meanings, so any symbol is ok if (ts.isExportAssignment(location.parent)) { @@ -129553,11 +130819,10 @@ var ts; || symbolToSortTextIdMap[ts.getSymbolId(symbolOrigin)] === 11 /* LocationPriority */)) { return false; } - // Continue with origin symbol - symbol = symbolOrigin; + allFlags |= ts.getCombinedLocalAndExportSymbolFlags(symbolOrigin); // import m = /**/ <-- It can only access namespace (if typing import = x. this would get member symbols and not namespace) if (ts.isInRightSideOfInternalImportEqualsDeclaration(location)) { - return !!(symbol.flags & 1920 /* Namespace */); + return !!(allFlags & 1920 /* Namespace */); } if (isTypeOnlyLocation) { // It's a type, but you can reach it by namespace.type as well @@ -129565,7 +130830,7 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 111551 /* Value */); + return !!(allFlags & 111551 /* Value */); } } Completions.getCompletionEntriesFromSymbols = getCompletionEntriesFromSymbols; @@ -129699,14 +130964,13 @@ var ts; Completions.createCompletionDetails = createCompletionDetails; function getCompletionEntryCodeActionsAndSourceDisplay(name, location, contextToken, origin, symbol, program, host, compilerOptions, sourceFile, position, previousToken, formatContext, preferences, data, source) { if (data === null || data === void 0 ? void 0 : data.moduleSpecifier) { - var _a = getRelevantTokens(position, sourceFile), contextToken_3 = _a.contextToken, previousToken_2 = _a.previousToken; - if (previousToken_2 && getImportStatementCompletionInfo(contextToken_3 || previousToken_2).replacementNode) { + if (previousToken && getImportStatementCompletionInfo(contextToken || previousToken).replacementNode) { // Import statement completion: 'import c|' return { codeActions: undefined, sourceDisplay: [ts.textPart(data.moduleSpecifier)] }; } } if (source === CompletionSource.ClassMemberSnippet) { - var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken).importAdder; + var importAdder = getEntryForMemberCompletion(host, program, compilerOptions, preferences, name, symbol, location, contextToken, formatContext).importAdder; if (importAdder) { var changes = ts.textChanges.ChangeTracker.with({ host: host, formatContext: formatContext, preferences: preferences }, importAdder.writeFixes); return { @@ -129718,13 +130982,19 @@ var ts; }; } } + if (originIsTypeOnlyAlias(origin)) { + var codeAction_1 = ts.codefix.getPromoteTypeOnlyCompletionAction(sourceFile, origin.declaration.name, program, host, formatContext, preferences); + ts.Debug.assertIsDefined(codeAction_1, "Expected to have a code action for promoting type-only alias"); + return { codeActions: [codeAction_1], sourceDisplay: undefined }; + } if (!origin || !(originIsExport(origin) || originIsResolvedExport(origin))) { return { codeActions: undefined, sourceDisplay: undefined }; } var checker = origin.isFromPackageJson ? host.getPackageJsonAutoImportProvider().getTypeChecker() : program.getTypeChecker(); var moduleSymbol = origin.moduleSymbol; var targetSymbol = checker.getMergedSymbol(ts.skipAlias(symbol.exportSymbol || symbol, checker)); - var _b = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions)), host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _b.moduleSpecifier, codeAction = _b.codeAction; + var isJsxOpeningTagName = (contextToken === null || contextToken === void 0 ? void 0 : contextToken.kind) === 29 /* LessThanToken */ && ts.isJsxOpeningLikeElement(contextToken.parent); + var _a = ts.codefix.getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, ts.getNameForExportedSymbol(symbol, ts.getEmitScriptTarget(compilerOptions), isJsxOpeningTagName), isJsxOpeningTagName, host, program, formatContext, previousToken && ts.isIdentifier(previousToken) ? previousToken.getStart(sourceFile) : position, preferences), moduleSpecifier = _a.moduleSpecifier, codeAction = _a.codeAction; ts.Debug.assert(!(data === null || data === void 0 ? void 0 : data.moduleSpecifier) || moduleSpecifier === data.moduleSpecifier); return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } @@ -129779,7 +131049,8 @@ var ts; case 103 /* NewKeyword */: return checker.getContextualType(parent); case 82 /* CaseKeyword */: - return ts.getSwitchedType(ts.cast(parent, ts.isCaseClause), checker); + var caseClause = ts.tryCast(parent, ts.isCaseClause); + return caseClause ? ts.getSwitchedType(caseClause, checker) : undefined; case 18 /* OpenBraceToken */: return ts.isJsxExpression(parent) && !ts.isJsxElement(parent.parent) && !ts.isJsxFragment(parent.parent) ? checker.getContextualTypeForJsxAttribute(parent.parent) : undefined; default: @@ -130104,6 +131375,7 @@ var ts; symbolToSortTextIdMap: symbolToSortTextIdMap, isTypeOnlyLocation: isTypeOnlyLocation, isJsxIdentifierExpected: isJsxIdentifierExpected, + isRightOfOpenTag: isRightOfOpenTag, importCompletionNode: importCompletionNode, hasUnresolvedAutoImports: hasUnresolvedAutoImports, }; @@ -130182,9 +131454,7 @@ var ts; // GH#39946. Pulling on the type of a node inside of a function with a contextual `this` parameter can result in a circularity // if the `node` is part of the exprssion of a `yield` or `return`. This circularity doesn't exist at compile time because // we will check (and cache) the type of `this` *before* checking the type of the node. - var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); - if (!ts.isSourceFile(container) && container.parent) - typeChecker.getTypeAtLocation(container); + typeChecker.tryGetThisTypeAt(node, /*includeGlobalThis*/ false); var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { @@ -130395,21 +131665,29 @@ var ts; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); var symbolMeanings = (isTypeOnlyLocation ? 0 /* None */ : 111551 /* Value */) | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var typeOnlyAliasNeedsPromotion = previousToken && !ts.isValidTypeOnlyAliasUseSite(previousToken); symbols = ts.concatenate(symbols, typeChecker.getSymbolsInScope(scopeNode, symbolMeanings)); ts.Debug.assertEachIsDefined(symbols, "getSymbolsInScope() should all be defined"); - for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { - var symbol = symbols_1[_i]; + for (var i = 0; i < symbols.length; i++) { + var symbol = symbols[i]; if (!typeChecker.isArgumentsSymbol(symbol) && !ts.some(symbol.declarations, function (d) { return d.getSourceFile() === sourceFile; })) { symbolToSortTextIdMap[ts.getSymbolId(symbol)] = 15 /* GlobalsOrKeywords */; } + if (typeOnlyAliasNeedsPromotion && !(symbol.flags & 111551 /* Value */)) { + var typeOnlyAliasDeclaration = symbol.declarations && ts.find(symbol.declarations, ts.isTypeOnlyImportOrExportDeclaration); + if (typeOnlyAliasDeclaration) { + var origin = { kind: 64 /* TypeOnlyAlias */, declaration: typeOnlyAliasDeclaration }; + symbolToOriginInfoMap[i] = origin; + } + } } // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== 303 /* SourceFile */) { var thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType && !isProbablyGlobalType(thisType, sourceFile, typeChecker)) { - for (var _a = 0, _b = getPropertiesForCompletion(thisType, typeChecker); _a < _b.length; _a++) { - var symbol = _b[_a]; + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker); _i < _a.length; _i++) { + var symbol = _a[_i]; symbolToOriginInfoMap[symbols.length] = { kind: 1 /* ThisType */ }; symbols.push(symbol); symbolToSortTextIdMap[ts.getSymbolId(symbol)] = 14 /* SuggestedClassMembers */; @@ -130512,39 +131790,47 @@ var ts; var packageJsonAutoImportProvider = (_b = host.getPackageJsonAutoImportProvider) === null || _b === void 0 ? void 0 : _b.call(host); var packageJsonFilter = detailsEntryId ? undefined : ts.createPackageJsonImportFilter(sourceFile, preferences, host); resolvingModuleSpecifiers("collectAutoImports", host, program, sourceFile, preferences, !!importCompletionNode, function (context) { - exportInfo.forEach(sourceFile.path, function (info, symbolName, isFromAmbientModule, exportMapKey) { + exportInfo.search(sourceFile.path, + /*preferCapitalized*/ isRightOfOpenTag, function (symbolName, targetFlags) { if (!ts.isIdentifierText(symbolName, ts.getEmitScriptTarget(host.getCompilationSettings()))) - return; + return false; if (!detailsEntryId && ts.isStringANonContextualKeyword(symbolName)) + return false; + if (!isTypeOnlyLocation && !importCompletionNode && !(targetFlags & 111551 /* Value */)) + return false; + if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */))) + return false; + // Do not try to auto-import something with a lowercase first letter for a JSX tag + var firstChar = symbolName.charCodeAt(0); + if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */)) + return false; + if (detailsEntryId) + return true; + return charactersFuzzyMatchInString(symbolName, lowerCaseTokenText); + }, function (info, symbolName, isFromAmbientModule, exportMapKey) { + if (detailsEntryId && !ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); })) { return; - // `targetFlags` should be the same for each `info` - if (!isTypeOnlyLocation && !importCompletionNode && !(info[0].targetFlags & 111551 /* Value */)) - return; - if (isTypeOnlyLocation && !(info[0].targetFlags & (1536 /* Module */ | 788968 /* Type */))) + } + var defaultExportInfo = ts.find(info, isImportableExportInfo); + if (!defaultExportInfo) { return; - var isCompletionDetailsMatch = detailsEntryId && ts.some(info, function (i) { return detailsEntryId.source === ts.stripQuotes(i.moduleSymbol.name); }); - if (isCompletionDetailsMatch || !detailsEntryId && charactersFuzzyMatchInString(symbolName, lowerCaseTokenText)) { - var defaultExportInfo = ts.find(info, isImportableExportInfo); - if (!defaultExportInfo) { - return; - } - // If we don't need to resolve module specifiers, we can use any re-export that is importable at all - // (We need to ensure that at least one is importable to show a completion.) - var _a = context.tryResolve(info, isFromAmbientModule) || {}, _b = _a.exportInfo, exportInfo_1 = _b === void 0 ? defaultExportInfo : _b, moduleSpecifier = _a.moduleSpecifier; - var isDefaultExport = exportInfo_1.exportKind === 1 /* Default */; - var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo_1.symbol) || exportInfo_1.symbol; - pushAutoImportSymbol(symbol, { - kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, - moduleSpecifier: moduleSpecifier, - symbolName: symbolName, - exportMapKey: exportMapKey, - exportName: exportInfo_1.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo_1.symbol.name, - fileName: exportInfo_1.moduleFileName, - isDefaultExport: isDefaultExport, - moduleSymbol: exportInfo_1.moduleSymbol, - isFromPackageJson: exportInfo_1.isFromPackageJson, - }); } + // If we don't need to resolve module specifiers, we can use any re-export that is importable at all + // (We need to ensure that at least one is importable to show a completion.) + var _a = context.tryResolve(info, isFromAmbientModule) || {}, _b = _a.exportInfo, exportInfo = _b === void 0 ? defaultExportInfo : _b, moduleSpecifier = _a.moduleSpecifier; + var isDefaultExport = exportInfo.exportKind === 1 /* Default */; + var symbol = isDefaultExport && ts.getLocalSymbolForExportDefault(exportInfo.symbol) || exportInfo.symbol; + pushAutoImportSymbol(symbol, { + kind: moduleSpecifier ? 32 /* ResolvedExport */ : 4 /* Export */, + moduleSpecifier: moduleSpecifier, + symbolName: symbolName, + exportMapKey: exportMapKey, + exportName: exportInfo.exportKind === 2 /* ExportEquals */ ? "export=" /* ExportEquals */ : exportInfo.symbol.name, + fileName: exportInfo.moduleFileName, + isDefaultExport: isDefaultExport, + moduleSymbol: exportInfo.moduleSymbol, + isFromPackageJson: exportInfo.isFromPackageJson, + }); }); hasUnresolvedAutoImports = context.resolutionLimitExceeded(); }); @@ -130598,16 +131884,19 @@ var ts; return true; } if (contextToken.kind === 31 /* GreaterThanToken */ && contextToken.parent) { + // <Component<string> /**/ /> + // <Component<string> /**/ ><Component> + // - contextToken: GreaterThanToken (before cursor) + // - location: JsxSelfClosingElement or JsxOpeningElement + // - contextToken.parent === location + if (location === contextToken.parent && (location.kind === 279 /* JsxOpeningElement */ || location.kind === 278 /* JsxSelfClosingElement */)) { + return false; + } if (contextToken.parent.kind === 279 /* JsxOpeningElement */) { - // Two possibilities: - // 1. <div>/**/ - // - contextToken: GreaterThanToken (before cursor) - // - location: JSXElement - // - different parents (JSXOpeningElement, JSXElement) - // 2. <Component<string> /**/> - // - contextToken: GreaterThanToken (before cursor) - // - location: GreaterThanToken (after cursor) - // - same parent (JSXOpeningElement) + // <div>/**/ + // - contextToken: GreaterThanToken (before cursor) + // - location: JSXElement + // - different parents (JSXOpeningElement, JSXElement) return location.parent.kind !== 279 /* JsxOpeningElement */; } if (contextToken.parent.kind === 280 /* JsxClosingElement */ || contextToken.parent.kind === 278 /* JsxSelfClosingElement */) { @@ -131514,10 +132803,40 @@ var ts; function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; } + function getContextualKeywords(contextToken, position) { + var entries = []; + /** + * An `AssertClause` can come after an import declaration: + * import * from "foo" | + * import "foo" | + * or after a re-export declaration that has a module specifier: + * export { foo } from "foo" | + * Source: https://tc39.es/proposal-import-assertions/ + */ + if (contextToken) { + var file = contextToken.getSourceFile(); + var parent = contextToken.parent; + var tokenLine = file.getLineAndCharacterOfPosition(contextToken.end).line; + var currentLine = file.getLineAndCharacterOfPosition(position).line; + if ((ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent) && parent.moduleSpecifier) + && contextToken === parent.moduleSpecifier + && tokenLine === currentLine) { + entries.push({ + name: ts.tokenToString(129 /* AssertKeyword */), + kind: "keyword" /* keyword */, + kindModifiers: "" /* none */, + sortText: SortText.GlobalsOrKeywords, + }); + } + } + return entries; + } /** Get the corresponding JSDocTag node if the position is in a jsDoc comment */ function getJsDocTagAtPosition(node, position) { - var jsdoc = ts.findAncestor(node, ts.isJSDoc); - return jsdoc && jsdoc.tags && (ts.rangeContainsPosition(jsdoc, position) ? ts.findLast(jsdoc.tags, function (tag) { return tag.pos < position; }) : undefined); + return ts.findAncestor(node, function (n) { + return ts.isJSDocTag(n) && ts.rangeContainsPosition(n, position) ? true : + ts.isJSDoc(n) ? "quit" : false; + }); } function getPropertiesForObjectExpression(contextualType, completionsType, obj, checker) { var hasCompletionsType = completionsType && completionsType !== contextualType; @@ -131533,6 +132852,8 @@ var ts; // function f<T>(x: T) {} // f({ abc/**/: "" }) // `abc` is a member of `T` but only because it declares itself function hasDeclarationOtherThanSelf(member) { + if (!ts.length(member.declarations)) + return true; return ts.some(member.declarations, function (decl) { return decl.parent !== obj; }); } } @@ -131804,10 +133125,14 @@ var ts; /** True if symbol is a type or a module containing at least one type. */ function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules) { if (seenModules === void 0) { seenModules = new ts.Map(); } - var sym = ts.skipAlias(symbol.exportSymbol || symbol, checker); - return !!(sym.flags & 788968 /* Type */) || checker.isUnknownSymbol(sym) || - !!(sym.flags & 1536 /* Module */) && ts.addToSeen(seenModules, ts.getSymbolId(sym)) && - checker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + // Since an alias can be merged with a local declaration, we need to test both the alias and its target. + // This code used to just test the result of `skipAlias`, but that would ignore any locally introduced meanings. + return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(ts.skipAlias(symbol.exportSymbol || symbol, checker)); + function nonAliasCanBeReferencedAtTypeLocation(symbol) { + return !!(symbol.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol) || + !!(symbol.flags & 1536 /* Module */) && ts.addToSeen(seenModules, ts.getSymbolId(symbol)) && + checker.getExportsOfModule(symbol).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, checker, seenModules); }); + } } function isDeprecated(symbol, checker) { var declarations = ts.skipAlias(symbol, checker).declarations; @@ -132370,7 +133695,24 @@ var ts; function acquireOrUpdateDocument(fileName, path, compilationSettings, key, scriptSnapshot, version, acquiring, scriptKind) { scriptKind = ts.ensureScriptKind(fileName, scriptKind); var scriptTarget = scriptKind === 6 /* JSON */ ? 100 /* JSON */ : ts.getEmitScriptTarget(compilationSettings); + var oldBucketCount = buckets.size; var bucket = ts.getOrUpdate(buckets, key, function () { return new ts.Map(); }); + if (ts.tracing) { + if (buckets.size > oldBucketCount) { + // It is interesting, but not definitively problematic if a build requires multiple document registry buckets - + // perhaps they are for two projects that don't have any overlap. + // Bonus: these events can help us interpret the more interesting event below. + ts.tracing.instant("session" /* Session */, "createdDocumentRegistryBucket", { configFilePath: compilationSettings.configFilePath, key: key }); + } + // It is fairly suspicious to have one path in two buckets - you'd expect dependencies to have similar configurations. + // If this occurs unexpectedly, the fix is likely to synchronize the project settings. + // Skip .d.ts files to reduce noise (should also cover most of node_modules). + var otherBucketKey = !ts.fileExtensionIs(path, ".d.ts" /* Dts */) && + ts.forEachEntry(buckets, function (bucket, bucketKey) { return bucketKey !== key && bucket.has(path) && bucketKey; }); + if (otherBucketKey) { + ts.tracing.instant("session" /* Session */, "documentRegistryBucketOverlap", { path: path, key1: otherBucketKey, key2: key }); + } + } var bucketEntry = bucket.get(path); var entry = bucketEntry && getDocumentRegistryEntry(bucketEntry, scriptKind); if (!entry && externalCache) { @@ -133035,7 +134377,7 @@ var ts; ts.Debug.assert(parent.name === node); return true; case 202 /* BindingElement */: - return ts.isInJSFile(node) && ts.isRequireVariableDeclaration(parent); + return ts.isInJSFile(node) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(parent); default: return false; } @@ -133516,7 +134858,7 @@ var ts; function getTextSpan(node, sourceFile, endNode) { var start = node.getStart(sourceFile); var end = (endNode || node).getEnd(); - if (ts.isStringLiteralLike(node)) { + if (ts.isStringLiteralLike(node) && (end - start) > 2) { ts.Debug.assert(endNode === undefined); start += 1; end -= 1; @@ -134061,8 +135403,8 @@ var ts; var sourceId = ts.getNodeId(sourceFile); var seenSymbols = this.sourceFileToSeenSymbols[sourceId] || (this.sourceFileToSeenSymbols[sourceId] = new ts.Set()); var anyNewSymbols = false; - for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { - var sym = symbols_2[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var sym = symbols_1[_i]; anyNewSymbols = ts.tryAddToSet(seenSymbols, ts.getSymbolId(sym)) || anyNewSymbols; } return anyNewSymbols; @@ -134249,7 +135591,7 @@ var ts; var token = _a[_i]; if (!ts.isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; - var referenceSymbol = checker.getSymbolAtLocation(token); // See GH#19955 for why the type annotation is necessary + var referenceSymbol = checker.getSymbolAtLocation(token); if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || ts.isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { @@ -134435,7 +135777,7 @@ var ts; // Use the parent symbol if the location is commonjs require syntax on javascript files only. if (ts.isInJSFile(referenceLocation) && referenceLocation.parent.kind === 202 /* BindingElement */ - && ts.isRequireVariableDeclaration(referenceLocation.parent)) { + && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent)) { referenceSymbol = referenceLocation.parent.symbol; // The parent will not have a symbol if it's an ObjectBindingPattern (when destructuring is used). In // this case, just skip it, since the bound identifiers are not an alias of the import. @@ -134879,7 +136221,8 @@ var ts; } } else { - return nodeEntry(ref, 2 /* StringLiteral */); + return ts.isNoSubstitutionTemplateLiteral(ref) && !ts.rangeIsOnSingleLine(ref, sourceFile) ? undefined : + nodeEntry(ref, 2 /* StringLiteral */); } } }); @@ -135783,7 +137126,7 @@ var ts; : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) - ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), getCanonicalFileName(newImportFromPath), toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text) + ? ts.moduleSpecifiers.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, getCanonicalFileName(newImportFromPath), toImport.newFileName, ts.createModuleSpecifierResolutionHost(program, host), importLiteral.text) : undefined; }); }; @@ -136035,7 +137378,7 @@ var ts; return file && { reference: libReferenceDirective, fileName: file.fileName, file: file, unverified: false }; } if ((_a = sourceFile.resolvedModules) === null || _a === void 0 ? void 0 : _a.size()) { - var node = ts.getTokenAtPosition(sourceFile, position); + var node = ts.getTouchingToken(sourceFile, position); if (ts.isModuleSpecifierLike(node) && ts.isExternalModuleNameRelative(node.text) && sourceFile.resolvedModules.has(node.text, ts.getModeForUsageLocation(sourceFile, node))) { var verifiedFileName = (_b = sourceFile.resolvedModules.get(node.text, ts.getModeForUsageLocation(sourceFile, node))) === null || _b === void 0 ? void 0 : _b.resolvedFileName; var fileName = verifiedFileName || ts.resolvePath(ts.getDirectoryPath(sourceFile.fileName), node.text); @@ -136060,14 +137403,17 @@ var ts; if (node === sourceFile) { return undefined; } - var symbol = typeChecker.getSymbolAtLocation(node); + var symbol = getSymbol(node, typeChecker); if (!symbol) return undefined; var typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); var returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); var fromReturnType = returnType && definitionFromType(returnType, typeChecker, node); // If a function returns 'void' or some other type with no definition, just return the function definition. - return fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + var typeDefinitions = fromReturnType && fromReturnType.length !== 0 ? fromReturnType : definitionFromType(typeAtLocation, typeChecker, node); + return typeDefinitions.length ? typeDefinitions + : !(symbol.flags & 111551 /* Value */) && symbol.flags & 788968 /* Type */ ? getDefinitionFromSymbol(typeChecker, ts.skipAlias(symbol, typeChecker), node) + : undefined; } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function definitionFromType(type, checker, node) { @@ -136142,7 +137488,7 @@ var ts; return declaration.parent.kind === 268 /* NamedImports */; case 202 /* BindingElement */: case 253 /* VariableDeclaration */: - return ts.isInJSFile(declaration) && ts.isRequireVariableDeclaration(declaration); + return ts.isInJSFile(declaration) && ts.isVariableDeclarationInitializedToBareOrAccessedRequire(declaration); default: return false; } @@ -136440,7 +137786,27 @@ var ts; case 326 /* JSDocAugmentsTag */: return withNode(tag.class); case 342 /* JSDocTemplateTag */: - return addComment(tag.typeParameters.map(function (tp) { return tp.getText(); }).join(", ")); + var templateTag = tag; + var displayParts_3 = []; + if (templateTag.constraint) { + displayParts_3.push(ts.textPart(templateTag.constraint.getText())); + } + if (ts.length(templateTag.typeParameters)) { + if (ts.length(displayParts_3)) { + displayParts_3.push(ts.spacePart()); + } + var lastTypeParameter_1 = templateTag.typeParameters[templateTag.typeParameters.length - 1]; + ts.forEach(templateTag.typeParameters, function (tp) { + displayParts_3.push(namePart(tp.getText())); + if (lastTypeParameter_1 !== tp) { + displayParts_3.push.apply(displayParts_3, [ts.punctuationPart(27 /* CommaToken */), ts.spacePart()]); + } + }); + } + if (comment) { + displayParts_3.push.apply(displayParts_3, __spreadArray([ts.spacePart()], getDisplayPartsFromComment(comment, checker), true)); + } + return displayParts_3; case 341 /* JSDocTypeTag */: return withNode(tag.typeExpression); case 343 /* JSDocTypedefTag */: @@ -136832,7 +138198,7 @@ var ts; textSpan: ts.createTextSpanFromNode(declaration), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: containerName ? containerName.text : "", - containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, // TODO: GH#18217 Just use `container ? ...` + containerKind: containerName ? ts.getNodeKind(container) : "" /* unknown */, }; } })(NavigateTo = ts.NavigateTo || (ts.NavigateTo = {})); @@ -137425,6 +138791,9 @@ var ts; // We use 1 NavNode to represent 'A.B.C', but there are multiple source nodes. // Only merge module nodes that have the same chain. Don't merge 'A.B.C' with 'A'! function areSameModule(a, b) { + if (!a.body || !b.body) { + return a.body === b.body; + } return a.body.kind === b.body.kind && (a.body.kind !== 260 /* ModuleDeclaration */ || areSameModule(a.body, b.body)); } /** Merge source into target. Source should be thrown away after this is called. */ @@ -137925,7 +139294,7 @@ var ts; newImportSpecifiers.push(ts.factory.createImportSpecifier(/*isTypeOnly*/ false, ts.factory.createIdentifier("default"), defaultImport.importClause.name)); // TODO: GH#18217 } } - newImportSpecifiers.push.apply(newImportSpecifiers, ts.flatMap(namedImports, function (i) { return i.importClause.namedBindings.elements; })); // TODO: GH#18217 + newImportSpecifiers.push.apply(newImportSpecifiers, getNewImportSpecifiers(namedImports)); var sortedImportSpecifiers = sortSpecifiers(newImportSpecifiers); var importDecl = defaultImports.length > 0 ? defaultImports[0] @@ -138135,6 +139504,21 @@ var ts; return 6; } } + function getNewImportSpecifiers(namedImports) { + return ts.flatMap(namedImports, function (namedImport) { + return ts.map(tryGetNamedBindingElements(namedImport), function (importSpecifier) { + return importSpecifier.name && importSpecifier.propertyName && importSpecifier.name.escapedText === importSpecifier.propertyName.escapedText + ? ts.factory.updateImportSpecifier(importSpecifier, importSpecifier.isTypeOnly, /*propertyName*/ undefined, importSpecifier.name) + : importSpecifier; + }); + }); + } + function tryGetNamedBindingElements(namedImport) { + var _a; + return ((_a = namedImport.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings) && ts.isNamedImports(namedImport.importClause.namedBindings) + ? namedImport.importClause.namedBindings.elements + : undefined; + } })(OrganizeImports = ts.OrganizeImports || (ts.OrganizeImports = {})); })(ts || (ts = {})); /* @internal */ @@ -138177,7 +139561,7 @@ var ts; if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); - if (ts.isDeclaration(n) || ts.isVariableStatement(n) || ts.isReturnStatement(n) || n.kind === 1 /* EndOfFileToken */) { + if (ts.isDeclaration(n) || ts.isVariableStatement(n) || ts.isReturnStatement(n) || ts.isCallOrNewExpression(n) || n.kind === 1 /* EndOfFileToken */) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } if (ts.isFunctionLike(n) && ts.isBinaryExpression(n.parent) && ts.isPropertyAccessExpression(n.parent.left)) { @@ -139848,12 +141232,12 @@ var ts; : { invocation: info.invocation.node, argumentCount: info.argumentCount, argumentIndex: info.argumentIndex }; } SignatureHelp.getArgumentInfoForCompletions = getArgumentInfoForCompletions; - function getArgumentOrParameterListInfo(node, sourceFile) { + function getArgumentOrParameterListInfo(node, position, sourceFile) { var info = getArgumentOrParameterListAndIndex(node, sourceFile); if (!info) return undefined; var list = info.list, argumentIndex = info.argumentIndex; - var argumentCount = getArgumentCount(list); + var argumentCount = getArgumentCount(list, /*ignoreTrailingComma*/ ts.isInString(sourceFile, position, node)); if (argumentIndex !== 0) { ts.Debug.assertLessThan(argumentIndex, argumentCount); } @@ -139899,7 +141283,7 @@ var ts; // Case 3: // foo<T#, U#>(a#, #b#) -> The token is buried inside a list, and should give signature help // Find out if 'node' is an argument, a type argument, or neither - var info = getArgumentOrParameterListInfo(node, sourceFile); + var info = getArgumentOrParameterListInfo(node, position, sourceFile); if (!info) return undefined; var list = info.list, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -139968,8 +141352,8 @@ var ts; function countBinaryExpressionParameters(b) { return ts.isBinaryExpression(b.left) ? countBinaryExpressionParameters(b.left) + 1 : 2; } - function tryGetParameterInfo(startingToken, _position, sourceFile, checker) { - var info = getContextualSignatureLocationInfo(startingToken, sourceFile, checker); + function tryGetParameterInfo(startingToken, position, sourceFile, checker) { + var info = getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker); if (!info) return undefined; var contextualType = info.contextualType, argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -139981,7 +141365,7 @@ var ts; var invocation = { kind: 2 /* Contextual */, signature: ts.first(signatures), node: startingToken, symbol: chooseBetterSymbol(nonNullableContextualType.symbol) }; return { isTypeParameterList: false, invocation: invocation, argumentsSpan: argumentsSpan, argumentIndex: argumentIndex, argumentCount: argumentCount }; } - function getContextualSignatureLocationInfo(startingToken, sourceFile, checker) { + function getContextualSignatureLocationInfo(startingToken, sourceFile, position, checker) { if (startingToken.kind !== 20 /* OpenParenToken */ && startingToken.kind !== 27 /* CommaToken */) return undefined; var parent = startingToken.parent; @@ -139990,7 +141374,7 @@ var ts; case 168 /* MethodDeclaration */: case 212 /* FunctionExpression */: case 213 /* ArrowFunction */: - var info = getArgumentOrParameterListInfo(startingToken, sourceFile); + var info = getArgumentOrParameterListInfo(startingToken, position, sourceFile); if (!info) return undefined; var argumentIndex = info.argumentIndex, argumentCount = info.argumentCount, argumentsSpan = info.argumentsSpan; @@ -140037,7 +141421,7 @@ var ts; } return argumentIndex; } - function getArgumentCount(argumentsList) { + function getArgumentCount(argumentsList, ignoreTrailingComma) { // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '<comma>' 'b'. So, in this case the arg count will be 2. However, there @@ -140051,7 +141435,7 @@ var ts; // arg count of 3. var listChildren = argumentsList.getChildren(); var argumentCount = ts.countWhere(listChildren, function (arg) { return arg.kind !== 27 /* CommaToken */; }); - if (listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { + if (!ignoreTrailingComma && listChildren.length > 0 && ts.last(listChildren).kind === 27 /* CommaToken */) { argumentCount++; } return argumentCount; @@ -140997,7 +142381,7 @@ var ts; if (typeChecker.isArgumentsSymbol(symbol)) { return "local var" /* localVariableElement */; } - if (location.kind === 108 /* ThisKeyword */ && ts.isExpression(location)) { + if (location.kind === 108 /* ThisKeyword */ && ts.isExpression(location) || ts.isThisInTypeQuery(location)) { return "parameter" /* parameterElement */; } var flags = ts.getCombinedLocalAndExportSymbolFlags(symbol); @@ -141015,6 +142399,8 @@ var ts; } if (flags & 16 /* Function */) return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + // FIXME: getter and setter use the same symbol. And it is rare to use only setter without getter, so in most cases the symbol always has getter flag. + // So, even when the location is just on the declaration of setter, this function returns getter. if (flags & 32768 /* GetAccessor */) return "getter" /* memberGetAccessorElement */; if (flags & 65536 /* SetAccessor */) @@ -141043,18 +142429,7 @@ var ts; } return unionPropertyKind; } - // If we requested completions after `x.` at the top-level, we may be at a source file location. - switch (location.parent && location.parent.kind) { - // If we've typed a character of the attribute name, will be 'JsxAttribute', else will be 'JsxOpeningElement'. - case 279 /* JsxOpeningElement */: - case 277 /* JsxElement */: - case 278 /* JsxSelfClosingElement */: - return location.kind === 79 /* Identifier */ ? "property" /* memberVariableElement */ : "JSX attribute" /* jsxAttribute */; - case 284 /* JsxAttribute */: - return "JSX attribute" /* jsxAttribute */; - default: - return "property" /* memberVariableElement */; - } + return "property" /* memberVariableElement */; } return "" /* unknown */; } @@ -141101,7 +142476,7 @@ var ts; var symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); var symbolKind = semanticMeaning & 1 /* Value */ ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : "" /* unknown */; var hasAddedSymbolInfo = false; - var isThisExpression = location.kind === 108 /* ThisKeyword */ && ts.isInExpressionContext(location); + var isThisExpression = location.kind === 108 /* ThisKeyword */ && ts.isInExpressionContext(location) || ts.isThisInTypeQuery(location); var type; var printer; var documentationFromAlias; @@ -141112,9 +142487,24 @@ var ts; } // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { - // If it is accessor they are allowed only if location is at name of the accessor + // If symbol is accessor, they are allowed only if location is at declaration identifier of the accessor if (symbolKind === "getter" /* memberGetAccessorElement */ || symbolKind === "setter" /* memberSetAccessorElement */) { - symbolKind = "property" /* memberVariableElement */; + var declaration = ts.find(symbol.declarations, function (declaration) { return declaration.name === location; }); + if (declaration) { + switch (declaration.kind) { + case 171 /* GetAccessor */: + symbolKind = "getter" /* memberGetAccessorElement */; + break; + case 172 /* SetAccessor */: + symbolKind = "setter" /* memberSetAccessorElement */; + break; + default: + ts.Debug.assertNever(declaration); + } + } + else { + symbolKind = "property" /* memberVariableElement */; + } } var signature = void 0; type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location); @@ -141267,7 +142657,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(63 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, ts.isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -141428,6 +142818,8 @@ var ts; } // For properties, variables and local vars: show the type if (symbolKind === "property" /* memberVariableElement */ || + symbolKind === "getter" /* memberGetAccessorElement */ || + symbolKind === "setter" /* memberSetAccessorElement */ || symbolKind === "JSX attribute" /* jsxAttribute */ || symbolFlags & 3 /* Variable */ || symbolKind === "local var" /* localVariableElement */ || @@ -141497,8 +142889,20 @@ var ts; } } } + if (documentation.length === 0 && ts.isIdentifier(location) && symbol.valueDeclaration && ts.isBindingElement(symbol.valueDeclaration)) { + var declaration = symbol.valueDeclaration; + var parent = declaration.parent; + if (ts.isIdentifier(declaration.name) && ts.isObjectBindingPattern(parent)) { + var name_4 = ts.getTextOfIdentifierOrLiteral(declaration.name); + var objectType = typeChecker.getTypeAtLocation(parent); + documentation = ts.firstDefined(objectType.isUnion() ? objectType.types : [objectType], function (t) { + var prop = t.getProperty(name_4); + return prop ? prop.getDocumentationComment(typeChecker) : undefined; + }) || ts.emptyArray; + } + } if (tags.length === 0 && !hasMultipleSignatures) { - tags = symbol.getJsDocTags(typeChecker); + tags = symbol.getContextualJsDocTags(enclosingDeclaration, typeChecker); } if (documentation.length === 0 && documentationFromAlias) { documentation = documentationFromAlias; @@ -141861,6 +143265,7 @@ var ts; lastTrailingTriviaWasNewLine: function () { return wasNewLine; }, skipToEndOf: skipToEndOf, skipToStartOf: skipToStartOf, + getStartPos: function () { var _a; return (_a = lastTokenInfo === null || lastTokenInfo === void 0 ? void 0 : lastTokenInfo.token.pos) !== null && _a !== void 0 ? _a : scanner.getTokenPos(); }, }); lastTokenInfo = undefined; scanner.setText(undefined); @@ -142034,8 +143439,7 @@ var ts; } function isOnToken() { var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); - var startPos = lastTokenInfo ? lastTokenInfo.token.pos : scanner.getStartPos(); - return startPos < endPos && current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); + return current !== 1 /* EndOfFileToken */ && !ts.isTrivia(current); } function isOnEOF() { var current = lastTokenInfo ? lastTokenInfo.token.kind : scanner.getToken(); @@ -143223,7 +144627,7 @@ var ts; return 0; } function formatNodeGivenIndentation(node, sourceFileLike, languageVariant, initialIndentation, delta, formatContext) { - var range = { pos: 0, end: sourceFileLike.text.length }; + var range = { pos: node.pos, end: node.end }; return formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, function (scanner) { return formatSpanWorker(range, node, initialIndentation, delta, scanner, formatContext, 1 /* FormatSelection */, function (_) { return false; }, // assume that node does not have any errors sourceFileLike); }); } @@ -143274,6 +144678,15 @@ var ts; } } } + if (previousRange && formattingScanner.getStartPos() >= originalRange.end) { + var token = formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() : + formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token : + undefined; + if (token) { + processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, enclosingNode, previousRange, previousRangeStartLine, previousParent, enclosingNode, + /*dynamicIndentation*/ undefined); + } + } return edits; // local functions /** Tries to compute the indentation for a list element. @@ -143456,19 +144869,13 @@ var ts; processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation); }); // proceed any tokens in the node that are located after child nodes - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(node); - if (tokenInfo.token.end > node.end) { + if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) { break; } consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node); } - if (!node.parent && formattingScanner.isOnEOF()) { - var token = formattingScanner.readEOFTokenRange(); - if (token.end <= node.end && previousRange) { - processPair(token, sourceFile.getLineAndCharacterOfPosition(token.pos).line, node, previousRange, previousRangeStartLine, previousParent, contextNode, nodeDynamicIndentation); - } - } function processChildNode(child, inheritedIndentation, parent, parentDynamicIndentation, parentStartLine, undecoratedParentStartLine, isListItem, isFirstListItem) { var childStartPos = child.getStart(sourceFile); var childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line; @@ -143494,9 +144901,12 @@ var ts; if (child.getFullWidth() === 0) { return inheritedIndentation; } - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { // proceed any parent tokens that are located prior to child.getStart() var tokenInfo = formattingScanner.readTokenInfo(node); + if (tokenInfo.token.end > originalRange.end) { + return inheritedIndentation; + } if (tokenInfo.token.end > childStartPos) { if (tokenInfo.token.pos > childStartPos) { formattingScanner.skipToStartOf(child); @@ -143506,7 +144916,7 @@ var ts; } consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node); } - if (!formattingScanner.isOnToken()) { + if (!formattingScanner.isOnToken() || formattingScanner.getStartPos() >= originalRange.end) { return inheritedIndentation; } if (ts.isToken(child)) { @@ -143535,7 +144945,7 @@ var ts; var startLine = parentStartLine; if (listStartToken !== 0 /* Unknown */) { // introduce a new indentation scope for lists (including list start and end tokens) - while (formattingScanner.isOnToken()) { + while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.end > nodes.pos) { // stop when formatting scanner moves past the beginning of node list @@ -143571,7 +144981,7 @@ var ts; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0); } var listEndToken = getCloseTokenForOpenToken(listStartToken); - if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken()) { + if (listEndToken !== 0 /* Unknown */ && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) { var tokenInfo = formattingScanner.readTokenInfo(parent); if (tokenInfo.token.kind === 27 /* CommaToken */ && ts.isCallLikeExpression(parent)) { var commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line; @@ -143702,24 +145112,26 @@ var ts; // win in a conflict with lower priority rules. ts.forEachRight(rules, function (rule) { lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - switch (lineAction) { - case 2 /* LineRemoved */: - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode); - } - break; - case 1 /* LineAdded */: - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode); - } - break; - default: - ts.Debug.assert(lineAction === 0 /* None */); + if (dynamicIndentation) { + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true, contextNode); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); + } } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = trimTrailingWhitespaces && !(rule.action & 16 /* DeleteSpace */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -144436,6 +145848,8 @@ var ts; case 179 /* ConstructorType */: case 174 /* ConstructSignature */: return getList(node.typeParameters) || getList(node.parameters); + case 171 /* GetAccessor */: + return getList(node.parameters); case 256 /* ClassDeclaration */: case 225 /* ClassExpression */: case 257 /* InterfaceDeclaration */: @@ -144910,6 +146324,7 @@ var ts; ChangeTracker.prototype.delete = function (sourceFile, node) { this.deletedNodes.push({ sourceFile: sourceFile, node: node }); }; + /** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */ ChangeTracker.prototype.deleteNode = function (sourceFile, node, options) { if (options === void 0) { options = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }; } this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options)); @@ -145055,6 +146470,30 @@ var ts; var indent = sourceFile.text.slice(startPosition, fnStart); this.insertNodeAt(sourceFile, fnStart, tag, { preserveLeadingWhitespace: false, suffix: this.newLineCharacter + indent }); }; + ChangeTracker.prototype.createJSDocText = function (sourceFile, node) { + var comments = ts.flatMap(node.jsDoc, function (jsDoc) { + return ts.isString(jsDoc.comment) ? ts.factory.createJSDocText(jsDoc.comment) : jsDoc.comment; + }); + var jsDoc = ts.singleOrUndefined(node.jsDoc); + return jsDoc && ts.positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && ts.length(comments) === 0 ? undefined : + ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))); + }; + ChangeTracker.prototype.replaceJSDocComment = function (sourceFile, node, tags) { + this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), ts.factory.createJSDocComment(this.createJSDocText(sourceFile, node), ts.factory.createNodeArray(tags))); + }; + ChangeTracker.prototype.addJSDocTags = function (sourceFile, parent, newTags) { + var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); + var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags.some(function (tag, i) { + var merged = tryMergeJsdocTags(tag, newTag); + if (merged) + oldTags[i] = merged; + return !!merged; + }); }); + this.replaceJSDocComment(sourceFile, parent, __spreadArray(__spreadArray([], oldTags, true), unmergedNewTags, true)); + }; + ChangeTracker.prototype.filterJSDocTags = function (sourceFile, parent, predicate) { + this.replaceJSDocComment(sourceFile, parent, ts.filter(ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }), predicate)); + }; ChangeTracker.prototype.replaceRangeWithText = function (sourceFile, range, text) { this.changes.push({ kind: ChangeKind.Text, sourceFile: sourceFile, range: range, text: text }); }; @@ -145289,6 +146728,15 @@ var ts; ChangeTracker.prototype.insertExportModifier = function (sourceFile, node) { this.insertText(sourceFile, node.getStart(sourceFile), "export "); }; + ChangeTracker.prototype.insertImportSpecifierAtIndex = function (sourceFile, importSpecifier, namedImports, index) { + var prevSpecifier = namedImports.elements[index - 1]; + if (prevSpecifier) { + this.insertNodeInListAfter(sourceFile, prevSpecifier, importSpecifier); + } + else { + this.insertNodeBefore(sourceFile, namedImports.elements[0], importSpecifier, !ts.positionsAreOnSameLine(namedImports.elements[0].getStart(), namedImports.parent.parent.getStart(), sourceFile)); + } + }; /** * This function should be used to insert nodes in lists when nodes don't carry separators as the part of the node range, * i.e. arguments in arguments lists, parameters in parameter lists etc. @@ -145449,6 +146897,35 @@ var ts; return ChangeTracker; }()); textChanges_3.ChangeTracker = ChangeTracker; + function updateJSDocHost(parent) { + if (parent.kind !== 213 /* ArrowFunction */) { + return parent; + } + var jsDocNode = parent.parent.kind === 166 /* PropertyDeclaration */ ? + parent.parent : + parent.parent.parent; + jsDocNode.jsDoc = parent.jsDoc; + jsDocNode.jsDocCache = parent.jsDocCache; + return jsDocNode; + } + function tryMergeJsdocTags(oldTag, newTag) { + if (oldTag.kind !== newTag.kind) { + return undefined; + } + switch (oldTag.kind) { + case 338 /* JSDocParameterTag */: { + var oldParam = oldTag; + var newParam = newTag; + return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText + ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) + : undefined; + } + case 339 /* JSDocReturnTag */: + return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + case 341 /* JSDocTypeTag */: + return ts.factory.createJSDocTypeTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + } + } // find first non-whitespace position in the leading trivia of the node function startPositionToDeleteNodeInList(sourceFile, node) { return ts.skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); @@ -145527,19 +147004,13 @@ var ts; + ((!options.suffix || ts.endsWith(noIndent, options.suffix)) ? "" : options.suffix); } - function getFormatCodeSettingsForWriting(_a, sourceFile) { - var options = _a.options; - var shouldAutoDetectSemicolonPreference = !options.semicolons || options.semicolons === ts.SemicolonPreference.Ignore; - var shouldRemoveSemicolons = options.semicolons === ts.SemicolonPreference.Remove || shouldAutoDetectSemicolonPreference && !ts.probablyUsesSemicolons(sourceFile); - return __assign(__assign({}, options), { semicolons: shouldRemoveSemicolons ? ts.SemicolonPreference.Remove : ts.SemicolonPreference.Ignore }); - } /** Note: this may mutate `nodeIn`. */ function getFormattedTextOfNode(nodeIn, sourceFile, pos, _a, newLineCharacter, formatContext, validate) { var indentation = _a.indentation, prefix = _a.prefix, delta = _a.delta; var _b = getNonformattedText(nodeIn, sourceFile, newLineCharacter), node = _b.node, text = _b.text; if (validate) validate(node, text); - var formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); + var formatOptions = ts.getFormatCodeSettingsForWriting(formatContext, sourceFile); var initialIndentation = indentation !== undefined ? indentation : ts.formatting.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || ts.getLineStartPositionForPosition(pos, sourceFile) === pos); @@ -145587,6 +147058,7 @@ var ts; ts.setTextRangePosEnd(newNode, getPos(node), getEnd(node)); return newNode; } + textChanges_3.assignPositionsToNode = assignPositionsToNode; function assignPositionsToNodeArray(nodes, visitor, test, start, count) { var visited = ts.visitNodes(nodes, visitor, test, start, count); if (!visited) { @@ -145757,6 +147229,7 @@ var ts; clear: clear }; } + textChanges_3.createWriter = createWriter; function getInsertionPositionAtSourceFileTop(sourceFile) { var lastPrologue; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { @@ -146150,21 +147623,32 @@ var ts; var errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { + var assertion = getAssertion(context.sourceFile, context.span.start); + if (assertion === undefined) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, assertion); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, ts.Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + var assertion = getAssertion(diag.file, diag.start); + if (assertion) { + makeChange(changes, diag.file, assertion); + } + }); }, }); - function makeChange(changeTracker, sourceFile, pos) { - var token = ts.getTokenAtPosition(sourceFile, pos); - var assertion = ts.Debug.checkDefined(ts.findAncestor(token, function (n) { return ts.isAsExpression(n) || ts.isTypeAssertionExpression(n); }), "Expected to find an assertion expression"); + function makeChange(changeTracker, sourceFile, assertion) { var replacement = ts.isAsExpression(assertion) ? ts.factory.createAsExpression(assertion.expression, ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */)) : ts.factory.createTypeAssertion(ts.factory.createKeywordTypeNode(154 /* UnknownKeyword */), assertion.expression); changeTracker.replaceNode(sourceFile, assertion.expression, replacement); } + function getAssertion(sourceFile, pos) { + if (ts.isInJSFile(sourceFile)) + return undefined; + return ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), function (n) { return ts.isAsExpression(n) || ts.isTypeAssertionExpression(n); }); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -146177,7 +147661,7 @@ var ts; ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ts.Diagnostics.for_await_loops_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, ], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddEmptyExportDeclaration(context) { var sourceFile = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { var exportDeclaration = ts.factory.createExportDeclaration( @@ -146206,7 +147690,7 @@ var ts; codefix.registerCodeFix({ fixIds: [fixId], errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingAsync(context) { var sourceFile = context.sourceFile, errorCode = context.errorCode, cancellationToken = context.cancellationToken, program = context.program, span = context.span; var diagnostic = ts.find(program.getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile, cancellationToken), getIsMatchingAsyncError(span, errorCode)); var directSpan = diagnostic && diagnostic.relatedInformation && ts.find(diagnostic.relatedInformation, function (r) { return r.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code; }); @@ -146303,7 +147787,7 @@ var ts; codefix.registerCodeFix({ fixIds: [fixId], errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingAwait(context) { var sourceFile = context.sourceFile, errorCode = context.errorCode, span = context.span, cancellationToken = context.cancellationToken, program = context.program; var expression = getAwaitErrorSpanExpression(sourceFile, errorCode, span, cancellationToken, program); if (!expression) { @@ -146535,7 +148019,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingConst(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start, context.program); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_const_to_unresolved_variable, fixId, ts.Diagnostics.Add_const_to_all_unresolved_variables)]; @@ -146635,7 +148119,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingDeclareOnProperty(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Prefix_with_declare, fixId, ts.Diagnostics.Prefix_all_incorrect_property_declarations_with_declare)]; @@ -146669,7 +148153,7 @@ var ts; var errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingInvocationForDecorator(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Call_decorator_expression, fixId, ts.Diagnostics.Add_to_all_uncalled_decorators)]; }, @@ -146694,7 +148178,7 @@ var ts; var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; }, @@ -148306,8 +149790,6 @@ var ts; var importSpecifiers = ts.mapAllOrFail(name.elements, function (e) { return e.dotDotDotToken || e.initializer || e.propertyName && !ts.isIdentifier(e.propertyName) || !ts.isIdentifier(e.name) ? undefined - // (TODO: GH#18217) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text); }); if (importSpecifiers) { @@ -148498,14 +149980,14 @@ var ts; var fixId = "convertToTypeOnlyExport"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context); }); if (changes.length) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_type_only_export, fixId, ts.Diagnostics.Convert_all_re_exported_types_to_type_only_exports)]; } }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { var fixedExportDeclarations = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var exportSpecifier = getExportSpecifierForDiagnosticSpan(diag, context.sourceFile); @@ -148566,7 +150048,7 @@ var ts; var fixId = "convertToTypeOnlyImport"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { var importDeclaration = getImportDeclarationForDiagnosticSpan(context.span, context.sourceFile); fixSingleImportDeclaration(t, importDeclaration, context); @@ -148576,7 +150058,7 @@ var ts; } }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var importDeclaration = getImportDeclarationForDiagnosticSpan(diag, context.sourceFile); fixSingleImportDeclaration(changes, importDeclaration, context); @@ -148615,7 +150097,7 @@ var ts; var errorCodes = [ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { var sourceFile = context.sourceFile, span = context.span; var info = getInfo(sourceFile, span.start); if (!info) { @@ -148757,7 +150239,8 @@ var ts; ts.Diagnostics.Cannot_find_namespace_0.code, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here.code, - ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code + ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer.code, + ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code, ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -148766,9 +150249,10 @@ var ts; var info = getFixesInfo(context, errorCode, span.start, /*useAutoImportProvider*/ true); if (!info) return undefined; - var fixes = info.fixes, symbolName = info.symbolName; + var fixes = info.fixes, symbolName = info.symbolName, errorIdentifierText = info.errorIdentifierText; var quotePreference = ts.getQuotePreference(sourceFile, preferences); - return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference, program.getCompilerOptions()); }); + return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, + /*includeSymbolNameInDescription*/ symbolName !== errorIdentifierText, quotePreference, program.getCompilerOptions()); }); }, fixIds: [importFixId], getAllCodeActions: function (context) { @@ -148803,11 +150287,11 @@ var ts; var symbolName = ts.getNameForExportedSymbol(exportedSymbol, ts.getEmitScriptTarget(compilerOptions)); var checker = program.getTypeChecker(); var symbol = checker.getMergedSymbol(ts.skipAlias(exportedSymbol, checker)); - var exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, host, program, preferences, useAutoImportProvider); + var exportInfo = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, /*isJsxTagName*/ false, host, program, preferences, useAutoImportProvider); var useRequire = shouldUseRequire(sourceFile, program); - var fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); + var fix = getImportFixForSymbol(sourceFile, exportInfo, moduleSymbol, symbolName, program, /*position*/ undefined, !!isValidTypeOnlyUseSite, useRequire, host, preferences); if (fix) { - addImport({ fixes: [fix], symbolName: symbolName }); + addImport({ fixes: [fix], symbolName: symbolName, errorIdentifierText: undefined }); } } function addImport(info) { @@ -148862,6 +150346,9 @@ var ts; } break; } + case 4 /* PromoteTypeOnly */: + // Excluding from fix-all + break; default: ts.Debug.assertNever(fix, "fix wasn't never - got kind ".concat(fix.kind)); } @@ -148953,6 +150440,7 @@ var ts; ImportFixKind[ImportFixKind["JsdocTypeImport"] = 1] = "JsdocTypeImport"; ImportFixKind[ImportFixKind["AddToExisting"] = 2] = "AddToExisting"; ImportFixKind[ImportFixKind["AddNew"] = 3] = "AddNew"; + ImportFixKind[ImportFixKind["PromoteTypeOnly"] = 4] = "PromoteTypeOnly"; })(ImportFixKind || (ImportFixKind = {})); // These should not be combined as bitflags, but are given powers of 2 values to // easily detect conflicts between `NotAllowed` and `Required` by giving them a unique sum. @@ -148964,23 +150452,33 @@ var ts; AddAsTypeOnly[AddAsTypeOnly["Required"] = 2] = "Required"; AddAsTypeOnly[AddAsTypeOnly["NotAllowed"] = 4] = "NotAllowed"; })(AddAsTypeOnly || (AddAsTypeOnly = {})); - function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, host, program, formatContext, position, preferences) { + function getImportCompletionAction(targetSymbol, moduleSymbol, sourceFile, symbolName, isJsxTagName, host, program, formatContext, position, preferences) { var compilerOptions = program.getCompilerOptions(); var exportInfos = ts.pathIsBareSpecifier(ts.stripQuotes(moduleSymbol.name)) ? [getSymbolExportInfoForSymbol(targetSymbol, moduleSymbol, program, host)] - : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, host, program, preferences, /*useAutoImportProvider*/ true); + : getAllReExportingModules(sourceFile, targetSymbol, moduleSymbol, symbolName, isJsxTagName, host, program, preferences, /*useAutoImportProvider*/ true); var useRequire = shouldUseRequire(sourceFile, program); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(ts.getTokenAtPosition(sourceFile, position)); var fix = ts.Debug.checkDefined(getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences)); return { moduleSpecifier: fix.moduleSpecifier, - codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, ts.getQuotePreference(sourceFile, preferences), compilerOptions)) + codeAction: codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, + /*includeSymbolNameInDescription*/ false, ts.getQuotePreference(sourceFile, preferences), compilerOptions)) }; } codefix.getImportCompletionAction = getImportCompletionAction; + function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, host, formatContext, preferences) { + var compilerOptions = program.getCompilerOptions(); + var symbolName = getSymbolName(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions); + var fix = getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program); + var includeSymbolNameInDescription = symbolName !== symbolToken.text; + return fix && codeFixActionToCodeAction(codeActionForFix({ host: host, formatContext: formatContext, preferences: preferences }, sourceFile, symbolName, fix, includeSymbolNameInDescription, 1 /* Double */, compilerOptions)); + } + codefix.getPromoteTypeOnlyCompletionAction = getPromoteTypeOnlyCompletionAction; function getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { ts.Debug.assert(exportInfos.some(function (info) { return info.moduleSymbol === moduleSymbol || info.symbol.parent === moduleSymbol; }), "Some exportInfo should match the specified moduleSymbol"); - return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, host, preferences); + var packageJsonImportFilter = ts.createPackageJsonImportFilter(sourceFile, preferences, host); + return getBestFix(getImportFixes(exportInfos, symbolName, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences), sourceFile, program, packageJsonImportFilter, host); } function codeFixActionToCodeAction(_a) { var description = _a.description, changes = _a.changes, commands = _a.commands; @@ -149006,7 +150504,7 @@ var ts; } } } - function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, host, program, preferences, useAutoImportProvider) { + function getAllReExportingModules(importingFile, targetSymbol, exportingModuleSymbol, symbolName, isJsxTagName, host, program, preferences, useAutoImportProvider) { var result = []; var compilerOptions = program.getCompilerOptions(); var getModuleSpecifierResolutionHost = ts.memoizeOne(function (isFromPackageJson) { @@ -149019,7 +150517,7 @@ var ts; return; } var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName) && ts.skipAlias(defaultInfo.symbol, checker) === targetSymbol && isImportable(program, moduleFile, isFromPackageJson)) { result.push({ symbol: defaultInfo.symbol, moduleSymbol: moduleSymbol, moduleFileName: moduleFile === null || moduleFile === void 0 ? void 0 : moduleFile.fileName, exportKind: defaultInfo.exportKind, targetFlags: ts.skipAlias(defaultInfo.symbol, checker).flags, isFromPackageJson: isFromPackageJson }); } for (var _i = 0, _a = checker.getExportsAndPropertiesOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -149035,12 +150533,12 @@ var ts; return !moduleFile || ts.isImportableFile(program, importingFile, moduleFile, preferences, /*packageJsonFilter*/ undefined, getModuleSpecifierResolutionHost(isFromPackageJson), (_a = host.getModuleSpecifierCache) === null || _a === void 0 ? void 0 : _a.call(host)); } } - function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences, fromCacheOnly) { + function getModuleSpecifierForBestExportInfo(exportInfo, importingFile, program, host, preferences, packageJsonImportFilter, fromCacheOnly) { var _a = getNewImportFixes(program, importingFile, /*position*/ undefined, /*isValidTypeOnlyUseSite*/ false, /*useRequire*/ false, exportInfo, host, preferences, fromCacheOnly), fixes = _a.fixes, computedWithoutCacheCount = _a.computedWithoutCacheCount; - var result = getBestFix(fixes, importingFile, program, host, preferences); + var result = getBestFix(fixes, importingFile, program, packageJsonImportFilter || ts.createPackageJsonImportFilter(importingFile, preferences, host), host); return result && __assign(__assign({}, result), { computedWithoutCacheCount: computedWithoutCacheCount }); } codefix.getModuleSpecifierForBestExportInfo = getModuleSpecifierForBestExportInfo; @@ -149174,7 +150672,7 @@ var ts; var importKind = getImportKind(importingFile, exportKind, compilerOptions); return ts.mapDefined(importingFile.imports, function (moduleSpecifier) { var i = ts.importFromModuleSpecifier(moduleSpecifier); - if (ts.isRequireVariableDeclaration(i.parent)) { + if (ts.isVariableDeclarationInitializedToRequire(i.parent)) { return checker.resolveExternalModuleName(moduleSpecifier) === moduleSymbol ? { declaration: i.parent, importKind: importKind, symbol: symbol, targetFlags: targetFlags } : undefined; } if (i.kind === 265 /* ImportDeclaration */ || i.kind === 264 /* ImportEqualsDeclaration */) { @@ -149210,7 +150708,7 @@ var ts; // 5. Literally nothing to go on return true; } - function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, moduleSymbols, host, preferences, fromCacheOnly) { + function getNewImportFixes(program, sourceFile, position, isValidTypeOnlyUseSite, useRequire, exportInfo, host, preferences, fromCacheOnly) { var isJs = ts.isSourceFileJS(sourceFile); var compilerOptions = program.getCompilerOptions(); var moduleSpecifierResolutionHost = ts.createModuleSpecifierResolutionHost(program, host); @@ -149219,7 +150717,7 @@ var ts; ? function (moduleSymbol) { return ({ moduleSpecifiers: ts.moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }); } : function (moduleSymbol, checker) { return ts.moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences); }; var computedWithoutCacheCount = 0; - var fixes = ts.flatMap(moduleSymbols, function (exportInfo) { + var fixes = ts.flatMap(exportInfo, function (exportInfo, i) { var checker = getChecker(exportInfo.isFromPackageJson); var _a = getModuleSpecifiers(exportInfo.moduleSymbol, checker), computedWithoutCache = _a.computedWithoutCache, moduleSpecifiers = _a.moduleSpecifiers; var importedSymbolHasValueMeaning = !!(exportInfo.targetFlags & 111551 /* Value */); @@ -149228,7 +150726,7 @@ var ts; return moduleSpecifiers === null || moduleSpecifiers === void 0 ? void 0 : moduleSpecifiers.map(function (moduleSpecifier) { // `position` should only be undefined at a missing jsx namespace, in which case we shouldn't be looking for pure types. return !importedSymbolHasValueMeaning && isJs && position !== undefined - ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo } + ? { kind: 1 /* JsdocTypeImport */, moduleSpecifier: moduleSpecifier, position: position, exportInfo: exportInfo, isReExport: i > 0 } : { kind: 3 /* AddNew */, moduleSpecifier: moduleSpecifier, @@ -149236,6 +150734,7 @@ var ts; useRequire: useRequire, addAsTypeOnly: addAsTypeOnly, exportInfo: exportInfo, + isReExport: i > 0, }; }); }); @@ -149257,37 +150756,69 @@ var ts; } function getFixesInfo(context, errorCode, pos, useAutoImportProvider) { var symbolToken = ts.getTokenAtPosition(context.sourceFile, pos); - var info = errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code - ? getFixesInfoForUMDImport(context, symbolToken) - : ts.isIdentifier(symbolToken) ? getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider) : undefined; - return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, context.host, context.preferences) }); + var info; + if (errorCode === ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead.code) { + info = getFixesInfoForUMDImport(context, symbolToken); + } + else if (!ts.isIdentifier(symbolToken)) { + return undefined; + } + else if (errorCode === ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type.code) { + var symbolName_1 = getSymbolName(context.sourceFile, context.program.getTypeChecker(), symbolToken, context.program.getCompilerOptions()); + var fix = getTypeOnlyPromotionFix(context.sourceFile, symbolToken, symbolName_1, context.program); + return fix && { fixes: [fix], symbolName: symbolName_1, errorIdentifierText: symbolToken.text }; + } + else { + info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); + } + var packageJsonImportFilter = ts.createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); + return info && __assign(__assign({}, info), { fixes: sortFixes(info.fixes, context.sourceFile, context.program, packageJsonImportFilter, context.host) }); } - function sortFixes(fixes, sourceFile, program, host, preferences) { - var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; - return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, allowsImportingSpecifier); }); + function sortFixes(fixes, sourceFile, program, packageJsonImportFilter, host) { + var _toPath = function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }; + return ts.sort(fixes, function (a, b) { return ts.compareValues(a.kind, b.kind) || compareModuleSpecifiers(a, b, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath); }); } - function getBestFix(fixes, sourceFile, program, host, preferences) { + function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { if (!ts.some(fixes)) return; // These will always be placed first if available, and are better than other kinds if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { return fixes[0]; } - var allowsImportingSpecifier = ts.createPackageJsonImportFilter(sourceFile, preferences, host).allowsImportingSpecifier; return fixes.reduce(function (best, fix) { // Takes true branch of conditional if `fix` is better than `best` - return compareModuleSpecifiers(fix, best, sourceFile, program, allowsImportingSpecifier) === -1 /* LessThan */ ? fix : best; + return compareModuleSpecifiers(fix, best, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), ts.hostGetCanonicalFileName(host)); }) === -1 /* LessThan */ ? fix : best; }); } /** @returns `Comparison.LessThan` if `a` is better than `b`. */ - function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier) { + function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { return ts.compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) + || ts.compareBooleans(isFixPossiblyReExportingImportingFile(a, importingFile, program.getCompilerOptions(), toPath), isFixPossiblyReExportingImportingFile(b, importingFile, program.getCompilerOptions(), toPath)) || ts.compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } return 0 /* EqualTo */; } + // This is a simple heuristic to try to avoid creating an import cycle with a barrel re-export. + // E.g., do not `import { Foo } from ".."` when you could `import { Foo } from "../Foo"`. + // This can produce false positives or negatives if re-exports cross into sibling directories + // (e.g. `export * from "../whatever"`) or are not named "index" (we don't even try to consider + // this if we're in a resolution mode where you can't drop trailing "/index" from paths). + function isFixPossiblyReExportingImportingFile(fix, importingFile, compilerOptions, toPath) { + var _a; + if (fix.isReExport && + ((_a = fix.exportInfo) === null || _a === void 0 ? void 0 : _a.moduleFileName) && + ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && + isIndexFileName(fix.exportInfo.moduleFileName)) { + var reExportDir = toPath(ts.getDirectoryPath(fix.exportInfo.moduleFileName)); + return ts.startsWith((importingFile.path), reExportDir); + } + return false; + } + function isIndexFileName(fileName) { + return ts.getBaseFileName(fileName, [".js", ".jsx", ".d.ts", ".ts", ".tsx"], /*ignoreCase*/ true) === "index"; + } function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { if (ts.startsWith(a, "node:") && !ts.startsWith(b, "node:")) return ts.shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */; @@ -149296,6 +150827,7 @@ var ts; return 0 /* EqualTo */; } function getFixesInfoForUMDImport(_a, token) { + var _b; var sourceFile = _a.sourceFile, program = _a.program, host = _a.host, preferences = _a.preferences; var checker = program.getTypeChecker(); var umdSymbol = getUmdSymbol(token, checker); @@ -149303,10 +150835,10 @@ var ts; return undefined; var symbol = checker.getAliasedSymbol(umdSymbol); var symbolName = umdSymbol.name; - var exportInfos = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }]; + var exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: undefined, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }]; var useRequire = shouldUseRequire(sourceFile, program); - var fixes = getImportFixes(exportInfos, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences); - return { fixes: fixes, symbolName: symbolName }; + var fixes = getImportFixes(exportInfo, symbolName, ts.isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*isValidTypeOnlyUseSite*/ false, useRequire, program, sourceFile, host, preferences); + return { fixes: fixes, symbolName: symbolName, errorIdentifierText: (_b = ts.tryCast(token, ts.isIdentifier)) === null || _b === void 0 ? void 0 : _b.text }; } function getUmdSymbol(token, checker) { // try the identifier to see if it is the umd symbol @@ -149372,12 +150904,22 @@ var ts; ts.Debug.assert(symbolName !== "default" /* Default */, "'default' isn't a legal identifier and couldn't occur here"); var isValidTypeOnlyUseSite = ts.isValidTypeOnlyAliasUseSite(symbolToken); var useRequire = shouldUseRequire(sourceFile, program); - var exportInfos = getExportInfos(symbolName, ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); - var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfos.entries(), function (_a) { + var exportInfo = getExportInfos(symbolName, ts.isJSXTagName(symbolToken), ts.getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host, preferences); + var fixes = ts.arrayFrom(ts.flatMapIterator(exportInfo.entries(), function (_a) { var _ = _a[0], exportInfos = _a[1]; return getImportFixes(exportInfos, symbolName, symbolToken.getStart(sourceFile), isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences); })); - return { fixes: fixes, symbolName: symbolName }; + return { fixes: fixes, symbolName: symbolName, errorIdentifierText: symbolToken.text }; + } + function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName, program) { + var checker = program.getTypeChecker(); + var symbol = checker.resolveName(symbolName, symbolToken, 111551 /* Value */, /*excludeGlobals*/ true); + if (!symbol) + return undefined; + var typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); + if (!typeOnlyAliasDeclaration || ts.getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) + return undefined; + return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration: typeOnlyAliasDeclaration }; } function jsxModeNeedsExplicitImport(jsx) { return jsx === 2 /* React */ || jsx === 3 /* ReactNative */; @@ -149386,14 +150928,20 @@ var ts; var parent = symbolToken.parent; if ((ts.isJsxOpeningLikeElement(parent) || ts.isJsxClosingElement(parent)) && parent.tagName === symbolToken && jsxModeNeedsExplicitImport(compilerOptions.jsx)) { var jsxNamespace = checker.getJsxNamespace(sourceFile); - if (ts.isIntrinsicJsxName(symbolToken.text) || !checker.resolveName(jsxNamespace, parent, 111551 /* Value */, /*excludeGlobals*/ true)) { + if (needsJsxNamespaceFix(jsxNamespace, symbolToken, checker)) { return jsxNamespace; } } return symbolToken.text; } + function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { + if (ts.isIntrinsicJsxName(symbolToken.text)) + return true; // If we were triggered by a matching error code on an intrinsic, the error must have been about missing the JSX factory + var namespaceSymbol = checker.resolveName(jsxNamespace, symbolToken, 111551 /* Value */, /*excludeGlobals*/ true); + return !namespaceSymbol || ts.some(namespaceSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration) && !(namespaceSymbol.flags & 111551 /* Value */); + } // Returns a map from an exported symbol's ID to a list of every way it's (re-)exported. - function getExportInfos(symbolName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { + function getExportInfos(symbolName, isJsxTagName, currentTokenMeaning, cancellationToken, fromFile, program, useAutoImportProvider, host, preferences) { var _a; // For each original symbol, keep all re-exports of that symbol together so we can call `getCodeActionsForImport` on the whole group at once. // Maps symbol id to info for modules providing that symbol (original export + re-exports). @@ -149416,7 +150964,7 @@ var ts; cancellationToken.throwIfCancellationRequested(); var compilerOptions = program.getCompilerOptions(); var defaultInfo = ts.getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions)) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { + if (defaultInfo && (defaultInfo.name === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, ts.getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName) && symbolHasMeaning(defaultInfo.symbolForMeaning, currentTokenMeaning)) { addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program, isFromPackageJson); } // check exports with the same name @@ -149456,14 +151004,14 @@ var ts; // allowSyntheticDefaultImports/esModuleInterop is enabled. return allowSyntheticDefaults ? 1 /* Default */ : 3 /* CommonJS */; } - function codeActionForFix(context, sourceFile, symbolName, fix, quotePreference, compilerOptions) { + function codeActionForFix(context, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions) { var diag; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { - diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference, compilerOptions); + diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions); }); return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } - function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference, compilerOptions) { + function codeActionForFixWorker(changes, sourceFile, symbolName, fix, includeSymbolNameInDescription, quotePreference, compilerOptions) { switch (fix.kind) { case 0 /* UseNamespace */: addNamespaceQualifier(changes, sourceFile, fix); @@ -149475,11 +151023,9 @@ var ts; var importClauseOrBindingPattern = fix.importClauseOrBindingPattern, importKind = fix.importKind, addAsTypeOnly = fix.addAsTypeOnly, moduleSpecifier = fix.moduleSpecifier; doAddExistingFix(changes, sourceFile, importClauseOrBindingPattern, importKind === 1 /* Default */ ? { name: symbolName, addAsTypeOnly: addAsTypeOnly } : undefined, importKind === 0 /* Named */ ? [{ name: symbolName, addAsTypeOnly: addAsTypeOnly }] : ts.emptyArray, compilerOptions); var moduleSpecifierWithoutQuotes = ts.stripQuotes(moduleSpecifier); - return [ - importKind === 1 /* Default */ ? ts.Diagnostics.Add_default_import_0_to_existing_import_declaration_from_1 : ts.Diagnostics.Add_0_to_existing_import_declaration_from_1, - symbolName, - moduleSpecifierWithoutQuotes - ]; // you too! + return includeSymbolNameInDescription + ? [ts.Diagnostics.Import_0_from_1, symbolName, moduleSpecifierWithoutQuotes] + : [ts.Diagnostics.Update_import_from_0, moduleSpecifierWithoutQuotes]; } case 3 /* AddNew */: { var importKind = fix.importKind, moduleSpecifier = fix.moduleSpecifier, addAsTypeOnly = fix.addAsTypeOnly, useRequire = fix.useRequire; @@ -149488,12 +151034,84 @@ var ts; var namedImports = importKind === 0 /* Named */ ? [{ name: symbolName, addAsTypeOnly: addAsTypeOnly }] : undefined; var namespaceLikeImport = importKind === 2 /* Namespace */ || importKind === 3 /* CommonJS */ ? { importKind: importKind, name: symbolName, addAsTypeOnly: addAsTypeOnly } : undefined; ts.insertImports(changes, sourceFile, getDeclarations(moduleSpecifier, quotePreference, defaultImport, namedImports, namespaceLikeImport), /*blankLineBetween*/ true); - return [importKind === 1 /* Default */ ? ts.Diagnostics.Import_default_0_from_module_1 : ts.Diagnostics.Import_0_from_module_1, symbolName, moduleSpecifier]; + return includeSymbolNameInDescription + ? [ts.Diagnostics.Import_0_from_1, symbolName, moduleSpecifier] + : [ts.Diagnostics.Add_import_from_0, moduleSpecifier]; + } + case 4 /* PromoteTypeOnly */: { + var typeOnlyAliasDeclaration = fix.typeOnlyAliasDeclaration; + var promotedDeclaration = promoteFromTypeOnly(changes, typeOnlyAliasDeclaration, compilerOptions, sourceFile); + return promotedDeclaration.kind === 269 /* ImportSpecifier */ + ? [ts.Diagnostics.Remove_type_from_import_of_0_from_1, symbolName, getModuleSpecifierText(promotedDeclaration.parent.parent)] + : [ts.Diagnostics.Remove_type_from_import_declaration_from_0, getModuleSpecifierText(promotedDeclaration)]; } default: return ts.Debug.assertNever(fix, "Unexpected fix kind ".concat(fix.kind)); } } + function getModuleSpecifierText(promotedDeclaration) { + var _a, _b; + return promotedDeclaration.kind === 264 /* ImportEqualsDeclaration */ + ? ((_b = ts.tryCast((_a = ts.tryCast(promotedDeclaration.moduleReference, ts.isExternalModuleReference)) === null || _a === void 0 ? void 0 : _a.expression, ts.isStringLiteralLike)) === null || _b === void 0 ? void 0 : _b.text) || promotedDeclaration.moduleReference.getText() + : ts.cast(promotedDeclaration.parent.moduleSpecifier, ts.isStringLiteral).text; + } + function promoteFromTypeOnly(changes, aliasDeclaration, compilerOptions, sourceFile) { + // See comment in `doAddExistingFix` on constant with the same name. + var convertExistingToTypeOnly = compilerOptions.preserveValueImports && compilerOptions.isolatedModules; + switch (aliasDeclaration.kind) { + case 269 /* ImportSpecifier */: + if (aliasDeclaration.isTypeOnly) { + if (aliasDeclaration.parent.elements.length > 1 && ts.OrganizeImports.importSpecifiersAreSorted(aliasDeclaration.parent.elements)) { + changes.delete(sourceFile, aliasDeclaration); + var newSpecifier = ts.factory.updateImportSpecifier(aliasDeclaration, /*isTypeOnly*/ false, aliasDeclaration.propertyName, aliasDeclaration.name); + var insertionIndex = ts.OrganizeImports.getImportSpecifierInsertionIndex(aliasDeclaration.parent.elements, newSpecifier); + changes.insertImportSpecifierAtIndex(sourceFile, newSpecifier, aliasDeclaration.parent, insertionIndex); + } + else { + changes.deleteRange(sourceFile, aliasDeclaration.getFirstToken()); + } + return aliasDeclaration; + } + else { + ts.Debug.assert(aliasDeclaration.parent.parent.isTypeOnly); + promoteImportClause(aliasDeclaration.parent.parent); + return aliasDeclaration.parent.parent; + } + case 266 /* ImportClause */: + promoteImportClause(aliasDeclaration); + return aliasDeclaration; + case 267 /* NamespaceImport */: + promoteImportClause(aliasDeclaration.parent); + return aliasDeclaration.parent; + case 264 /* ImportEqualsDeclaration */: + changes.deleteRange(sourceFile, aliasDeclaration.getChildAt(1)); + return aliasDeclaration; + default: + ts.Debug.failBadSyntaxKind(aliasDeclaration); + } + function promoteImportClause(importClause) { + changes.delete(sourceFile, ts.getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); + if (convertExistingToTypeOnly) { + var namedImports = ts.tryCast(importClause.namedBindings, ts.isNamedImports); + if (namedImports && namedImports.elements.length > 1) { + if (ts.OrganizeImports.importSpecifiersAreSorted(namedImports.elements) && + aliasDeclaration.kind === 269 /* ImportSpecifier */ && + namedImports.elements.indexOf(aliasDeclaration) !== 0) { + // The import specifier being promoted will be the only non-type-only, + // import in the NamedImports, so it should be moved to the front. + changes.delete(sourceFile, aliasDeclaration); + changes.insertImportSpecifierAtIndex(sourceFile, aliasDeclaration, namedImports, 0); + } + for (var _i = 0, _a = namedImports.elements; _i < _a.length; _i++) { + var element = _a[_i]; + if (element !== aliasDeclaration && !element.isTypeOnly) { + changes.insertModifierBefore(sourceFile, 151 /* TypeKeyword */, element); + } + } + } + } + } + } function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImports, compilerOptions) { var _a; if (clause.kind === 200 /* ObjectBindingPattern */) { @@ -149531,13 +151149,7 @@ var ts; var insertionIndex = convertExistingToTypeOnly && !spec.isTypeOnly ? 0 : ts.OrganizeImports.getImportSpecifierInsertionIndex(existingSpecifiers, spec); - var prevSpecifier = clause.namedBindings.elements[insertionIndex - 1]; - if (prevSpecifier) { - changes.insertNodeInListAfter(sourceFile, prevSpecifier, spec); - } - else { - changes.insertNodeBefore(sourceFile, existingSpecifiers[0], spec, !ts.positionsAreOnSameLine(existingSpecifiers[0].getStart(), clause.parent.getStart(), sourceFile)); - } + changes.insertImportSpecifierAtIndex(sourceFile, spec, clause.namedBindings, insertionIndex); } } else if (existingSpecifiers === null || existingSpecifiers === void 0 ? void 0 : existingSpecifiers.length) { @@ -149652,17 +151264,20 @@ var ts; var declarations = _a.declarations; return ts.some(declarations, function (decl) { return !!(ts.getMeaningFromDeclaration(decl) & meaning); }); } - function moduleSymbolToValidIdentifier(moduleSymbol, target) { - return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); + function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { + return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target, forceCapitalize); } codefix.moduleSymbolToValidIdentifier = moduleSymbolToValidIdentifier; - function moduleSpecifierToValidIdentifier(moduleSpecifier, target) { + function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { var baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); var res = ""; var lastCharWasValid = true; var firstCharCode = baseName.charCodeAt(0); if (ts.isIdentifierStart(firstCharCode, target)) { res += String.fromCharCode(firstCharCode); + if (forceCapitalize) { + res = res.toUpperCase(); + } } else { lastCharWasValid = false; @@ -149699,35 +151314,72 @@ var ts; ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code, - ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code + ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code, + ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code, + ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code, + ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code, ]; var errorCodeFixIdMap = (_a = {}, - _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, - ], - _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = [ - ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], - _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Add_all_missing_override_modifiers, - ], - _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = [ - ts.Diagnostics.Add_override_modifier, fixAddOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], - _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = [ - ts.Diagnostics.Remove_override_modifier, fixRemoveOverrideId, ts.Diagnostics.Remove_all_unnecessary_override_modifiers - ], + // case #1: + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + _a[ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers + }, + // case #2: + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + _a[ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_override_modifier + }, + // case #3: + _a[ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + _a[ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Add_all_missing_override_modifiers, + }, + // case #4: + _a[ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Add_override_modifier, + fixId: fixAddOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + // case #5: + _a[ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, + _a[ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code] = { + descriptions: ts.Diagnostics.Remove_override_modifier, + fixId: fixRemoveOverrideId, + fixAllDescriptions: ts.Diagnostics.Remove_all_unnecessary_override_modifiers, + }, _a); codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var errorCode = context.errorCode, span = context.span, sourceFile = context.sourceFile; + getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { + var errorCode = context.errorCode, span = context.span; var info = errorCodeFixIdMap[errorCode]; if (!info) return ts.emptyArray; - var descriptions = info[0], fixId = info[1], fixAllDescriptions = info[2]; - if (ts.isSourceFileJS(sourceFile)) - return ts.emptyArray; + var descriptions = info.descriptions, fixId = info.fixId, fixAllDescriptions = info.fixAllDescriptions; var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { return dispatchChanges(changes, context, errorCode, span.start); }); return [ codefix.createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId, fixAllDescriptions) @@ -149736,9 +151388,9 @@ var ts; fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var code = diag.code, start = diag.start, file = diag.file; + var code = diag.code, start = diag.start; var info = errorCodeFixIdMap[code]; - if (!info || info[1] !== context.fixId || ts.isSourceFileJS(file)) { + if (!info || info.fixId !== context.fixId) { return; } dispatchChanges(changes, context, code, start); @@ -149748,11 +151400,15 @@ var ts; function dispatchChanges(changeTracker, context, errorCode, pos) { switch (errorCode) { case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0.code: + case ts.Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: case ts.Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code: case ts.Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0.code: + case ts.Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0.code: return doAddOverrideModifierChange(changeTracker, context.sourceFile, pos); case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code: + case ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0.code: case ts.Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code: + case ts.Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class.code: return doRemoveOverrideModifierChange(changeTracker, context.sourceFile, pos); default: ts.Debug.fail("Unexpected error code: " + errorCode); @@ -149760,6 +151416,10 @@ var ts; } function doAddOverrideModifierChange(changeTracker, sourceFile, pos) { var classElement = findContainerClassElementLike(sourceFile, pos); + if (ts.isSourceFileJS(sourceFile)) { + changeTracker.addJSDocTags(sourceFile, classElement, [ts.factory.createJSDocOverrideTag(ts.factory.createIdentifier("override"))]); + return; + } var modifiers = classElement.modifiers || ts.emptyArray; var staticModifier = ts.find(modifiers, ts.isStaticModifier); var abstractModifier = ts.find(modifiers, ts.isAbstractModifier); @@ -149773,6 +151433,10 @@ var ts; } function doRemoveOverrideModifierChange(changeTracker, sourceFile, pos) { var classElement = findContainerClassElementLike(sourceFile, pos); + if (ts.isSourceFileJS(sourceFile)) { + changeTracker.filterJSDocTags(sourceFile, classElement, ts.not(ts.isJSDocOverrideTag)); + return; + } var overrideModifier = classElement.modifiers && ts.find(classElement.modifiers, function (modifier) { return modifier.kind === 158 /* OverrideKeyword */; }); ts.Debug.assertIsDefined(overrideModifier); changeTracker.deleteModifier(sourceFile, overrideModifier); @@ -149846,7 +151510,7 @@ var ts; var errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixImplicitThis(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span; var diagnostic; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { @@ -149861,14 +151525,15 @@ var ts; }); function doChange(changes, sourceFile, pos, checker) { var token = ts.getTokenAtPosition(sourceFile, pos); - ts.Debug.assert(token.kind === 108 /* ThisKeyword */); + if (!ts.isThis(token)) + return undefined; var fn = ts.getThisContainer(token, /*includeArrowFunctions*/ false); if (!ts.isFunctionDeclaration(fn) && !ts.isFunctionExpression(fn)) return undefined; if (!ts.isSourceFile(ts.getThisContainer(fn, /*includeArrowFunctions*/ false))) { // 'this' is defined outside, convert to arrow function - var fnKeyword = ts.Debug.assertDefined(ts.findChildOfKind(fn, 98 /* FunctionKeyword */, sourceFile)); + var fnKeyword = ts.Debug.checkDefined(ts.findChildOfKind(fn, 98 /* FunctionKeyword */, sourceFile)); var name = fn.name; - var body = ts.Debug.assertDefined(fn.body); // Should be defined because the function contained a 'this' expression + var body = ts.Debug.checkDefined(fn.body); // Should be defined because the function contained a 'this' expression if (ts.isFunctionExpression(fn)) { if (name && ts.FindAllReferences.Core.isSymbolReferencedInFile(name, checker, sourceFile, body)) { // Function expression references itself. To fix we would have to extract it to a const. @@ -149906,7 +151571,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { var sourceFile = context.sourceFile, span = context.span; var namedTupleMember = getNamedTupleMember(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, namedTupleMember); }); @@ -150105,7 +151770,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToCorrectReturnValue(context) { var program = context.program, sourceFile = context.sourceFile, start = context.span.start, errorCode = context.errorCode; var info = getInfo(program.getTypeChecker(), sourceFile, start, errorCode); if (!info) @@ -150445,7 +152110,8 @@ var ts; return { kind: 3 /* ObjectLiteral */, token: token, properties: properties, indentation: undefined, parentDeclaration: parent.initializer }; } if (ts.isIdentifier(token) && ts.isJsxOpeningLikeElement(token.parent)) { - var attributes = getUnmatchedAttributes(checker, token.parent); + var target = ts.getEmitScriptTarget(program.getCompilerOptions()); + var attributes = getUnmatchedAttributes(checker, target, token.parent); if (!ts.length(attributes)) return undefined; return { kind: 4 /* JsxAttributes */, token: token, attributes: attributes, parentDeclaration: token.parent }; @@ -150680,8 +152346,12 @@ var ts; var jsxAttributesNode = info.parentDeclaration.attributes; var hasSpreadAttribute = ts.some(jsxAttributesNode.properties, ts.isJsxSpreadAttribute); var attrs = ts.map(info.attributes, function (attr) { - var value = attr.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(attr.valueDeclaration)) : createUndefined(); - return ts.factory.createJsxAttribute(ts.factory.createIdentifier(attr.name), ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); + var value = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(attr)); + var name = ts.factory.createIdentifier(attr.name); + var jsxAttribute = ts.factory.createJsxAttribute(name, ts.factory.createJsxExpression(/*dotDotDotToken*/ undefined, value)); + // formattingScanner requires the Identifier to have a context for scanning attributes with "-" (data-foo). + ts.setParent(name, jsxAttribute); + return jsxAttribute; }); var jsxAttributes = ts.factory.createJsxAttributes(hasSpreadAttribute ? __spreadArray(__spreadArray([], attrs, true), jsxAttributesNode.properties, true) : __spreadArray(__spreadArray([], jsxAttributesNode.properties, true), attrs, true)); var options = { prefix: jsxAttributesNode.pos === jsxAttributesNode.end ? " " : undefined }; @@ -150690,10 +152360,11 @@ var ts; function addObjectLiteralProperties(changes, context, info) { var importAdder = codefix.createImportAdder(context.sourceFile, context.program, context.preferences, context.host); var quotePreference = ts.getQuotePreference(context.sourceFile, context.preferences); + var target = ts.getEmitScriptTarget(context.program.getCompilerOptions()); var checker = context.program.getTypeChecker(); var props = ts.map(info.properties, function (prop) { - var initializer = prop.valueDeclaration ? tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeAtLocation(prop.valueDeclaration)) : createUndefined(); - return ts.factory.createPropertyAssignment(prop.name, initializer); + var initializer = tryGetValueFromType(context, checker, importAdder, quotePreference, checker.getTypeOfSymbol(prop)); + return ts.factory.createPropertyAssignment(ts.createPropertyNameNodeForIdentifierOrLiteral(prop.name, target, quotePreference === 0 /* Single */), initializer); }); var options = { leadingTriviaOption: ts.textChanges.LeadingTriviaOption.Exclude, @@ -150780,7 +152451,7 @@ var ts; return (type.flags & 524288 /* Object */) && ((ts.getObjectFlags(type) & 128 /* ObjectLiteral */) || (type.symbol && ts.tryCast(ts.singleOrUndefined(type.symbol.declarations), ts.isTypeLiteralNode))); } - function getUnmatchedAttributes(checker, source) { + function getUnmatchedAttributes(checker, target, source) { var attrsType = checker.getContextualType(source.attributes); if (attrsType === undefined) return ts.emptyArray; @@ -150802,7 +152473,7 @@ var ts; } } return ts.filter(targetProps, function (targetProp) { - return !((targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */) || seenNames.has(targetProp.escapedName)); + return ts.isIdentifierText(targetProp.name, target, 1 /* JSX */) && !((targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */) || seenNames.has(targetProp.escapedName)); }); } })(codefix = ts.codefix || (ts.codefix = {})); @@ -150855,7 +152526,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixNotFoundModule(context) { var host = context.host, sourceFile = context.sourceFile, start = context.span.start; var packageName = tryGetImportedPackageName(sourceFile, start); if (packageName === undefined) @@ -150916,7 +152587,7 @@ var ts; var fixId = "fixClassDoesntImplementInheritedAbstractMember"; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); @@ -150924,7 +152595,7 @@ var ts; return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { var seenClassDeclarations = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); @@ -151057,7 +152728,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToEnableExperimentalDecorators(context) { var configFile = context.program.getCompilerOptions().configFile; if (configFile === undefined) { return undefined; @@ -151088,7 +152759,7 @@ var ts; var errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { var configFile = context.program.getCompilerOptions().configFile; if (configFile === undefined) { return undefined; @@ -151126,7 +152797,7 @@ var ts; ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, ], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixModuleAndTarget(context) { var compilerOptions = context.program.getCompilerOptions(); var configFile = compilerOptions.configFile; if (configFile === undefined) { @@ -151338,6 +153009,95 @@ var ts; (function (ts) { var codefix; (function (codefix) { + var deleteUnmatchedParameter = "deleteUnmatchedParameter"; + var renameUnmatchedParameter = "renameUnmatchedParameter"; + var errorCodes = [ + ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code, + ]; + codefix.registerCodeFix({ + fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter], + errorCodes: errorCodes, + getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { + var sourceFile = context.sourceFile, span = context.span; + var actions = []; + var info = getInfo(sourceFile, span.start); + if (info) { + ts.append(actions, getDeleteAction(context, info)); + ts.append(actions, getRenameAction(context, info)); + return actions; + } + return undefined; + }, + getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { + var tagsToSignature = new ts.Map(); + return codefix.createCombinedCodeActions(ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.eachDiagnostic(context, errorCodes, function (_a) { + var file = _a.file, start = _a.start; + var info = getInfo(file, start); + if (info) { + tagsToSignature.set(info.signature, ts.append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); + } + }); + tagsToSignature.forEach(function (tags, signature) { + if (context.fixId === deleteUnmatchedParameter) { + var tagsSet_1 = new ts.Set(tags); + changes.filterJSDocTags(signature.getSourceFile(), signature, function (t) { return !tagsSet_1.has(t); }); + } + }); + })); + } + }); + function getDeleteAction(context, _a) { + var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag; + var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { + return changeTracker.filterJSDocTags(context.sourceFile, signature, function (t) { return t !== jsDocParameterTag; }); + }); + return codefix.createCodeFixAction(deleteUnmatchedParameter, changes, [ts.Diagnostics.Delete_unused_param_tag_0, name.getText(context.sourceFile)], deleteUnmatchedParameter, ts.Diagnostics.Delete_all_unused_param_tags); + } + function getRenameAction(context, _a) { + var name = _a.name, signature = _a.signature, jsDocParameterTag = _a.jsDocParameterTag; + if (!ts.length(signature.parameters)) + return undefined; + var sourceFile = context.sourceFile; + var tags = ts.getJSDocTags(signature); + var names = new ts.Set(); + for (var _i = 0, tags_2 = tags; _i < tags_2.length; _i++) { + var tag = tags_2[_i]; + if (ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name)) { + names.add(tag.name.escapedText); + } + } + // @todo - match to all available names instead to the first parameter name + // @see /codeFixRenameUnmatchedParameter3.ts + var parameterName = ts.firstDefined(signature.parameters, function (p) { + return ts.isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : undefined; + }); + if (parameterName === undefined) + return undefined; + var newJSDocParameterTag = ts.factory.updateJSDocParameterTag(jsDocParameterTag, jsDocParameterTag.tagName, ts.factory.createIdentifier(parameterName), jsDocParameterTag.isBracketed, jsDocParameterTag.typeExpression, jsDocParameterTag.isNameFirst, jsDocParameterTag.comment); + var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { + return changeTracker.replaceJSDocComment(sourceFile, signature, ts.map(tags, function (t) { return t === jsDocParameterTag ? newJSDocParameterTag : t; })); + }); + return codefix.createCodeFixActionWithoutFixAll(renameUnmatchedParameter, changes, [ts.Diagnostics.Rename_param_tag_name_0_to_1, name.getText(sourceFile), parameterName]); + } + function getInfo(sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (token.parent && ts.isJSDocParameterTag(token.parent) && ts.isIdentifier(token.parent.name)) { + var jsDocParameterTag = token.parent; + var signature = ts.getHostSignatureFromJSDoc(jsDocParameterTag); + if (signature) { + return { signature: signature, name: token.parent.name, jsDocParameterTag: jsDocParameterTag }; + } + } + return undefined; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { var fixName = "unusedIdentifier"; var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; @@ -151632,6 +153392,9 @@ var ts; case 172 /* SetAccessor */: // Setter must have a parameter return false; + case 171 /* GetAccessor */: + // Getter cannot have parameters + return true; default: return ts.Debug.failBadSyntaxKind(parent); } @@ -151665,6 +153428,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { + var syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); + if (syntacticDiagnostics.length) + return; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, context.sourceFile, context.span.start, context.span.length, context.errorCode); }); return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unreachable_code, fixId, ts.Diagnostics.Remove_all_unreachable_code)]; }, @@ -151886,6 +153652,7 @@ var ts; var errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, + ts.Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code ]; codefix.registerCodeFix({ errorCodes: errorCodes, @@ -151898,7 +153665,7 @@ var ts; return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_async_modifier_to_containing_function, fixId, ts.Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId], - getAllCodeActions: function (context) { + getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { var seen = new ts.Map(); return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var nodes = getNodes(diag.file, diag.start); @@ -152067,7 +153834,7 @@ var ts; }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined - : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; + : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), ts.getTextOfNode(name)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { @@ -152136,7 +153903,7 @@ var ts; if (typeNode) { // Note that the codefix will never fire with an existing `@type` tag, so there is no need to merge tags var typeTag = ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode), /*comment*/ undefined); - addJSDocTags(changes, sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); + changes.addJSDocTags(sourceFile, ts.cast(parent.parent.parent, ts.isExpressionStatement), [typeTag]); } importAdder.writeFixes(changes); return parent; @@ -152145,7 +153912,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, importAdder, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, importAdder, ts.getSourceFileOfNode(symbol.valueDeclaration), symbol.valueDeclaration, program, host, cancellationToken); importAdder.writeFixes(changes); return symbol.valueDeclaration; } @@ -152247,7 +154014,7 @@ var ts; } } function annotateJSDocThis(changes, sourceFile, containingFunction, typeNode) { - addJSDocTags(changes, sourceFile, containingFunction, [ + changes.addJSDocTags(sourceFile, containingFunction, [ ts.factory.createJSDocThisTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(typeNode)), ]); } @@ -152276,7 +154043,7 @@ var ts; } var typeExpression = ts.factory.createJSDocTypeExpression(typeNode); var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.factory.createJSDocReturnTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined) : ts.factory.createJSDocTypeTag(/*tagName*/ undefined, typeExpression, /*comment*/ undefined); - addJSDocTags(changes, sourceFile, parent, [typeTag]); + changes.addJSDocTags(sourceFile, parent, [typeTag]); } else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, declaration, sourceFile, changes, importAdder, ts.getEmitScriptTarget(program.getCompilerOptions()))) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); @@ -152332,45 +154099,7 @@ var ts; var name = _a.name, typeNode = _a.typeNode, isOptional = _a.isOptional; return ts.factory.createJSDocParameterTag(/*tagName*/ undefined, name, /*isBracketed*/ !!isOptional, ts.factory.createJSDocTypeExpression(typeNode), /* isNameFirst */ false, /*comment*/ undefined); }); - addJSDocTags(changes, sourceFile, signature, paramTags); - } - } - function addJSDocTags(changes, sourceFile, parent, newTags) { - var comments = ts.flatMap(parent.jsDoc, function (j) { return typeof j.comment === "string" ? ts.factory.createJSDocText(j.comment) : j.comment; }); - var oldTags = ts.flatMapToMutable(parent.jsDoc, function (j) { return j.tags; }); - var unmergedNewTags = newTags.filter(function (newTag) { return !oldTags || !oldTags.some(function (tag, i) { - var merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; - return !!merged; - }); }); - var tag = ts.factory.createJSDocComment(ts.factory.createNodeArray(ts.intersperse(comments, ts.factory.createJSDocText("\n"))), ts.factory.createNodeArray(__spreadArray(__spreadArray([], (oldTags || ts.emptyArray), true), unmergedNewTags, true))); - var jsDocNode = parent.kind === 213 /* ArrowFunction */ ? getJsDocNodeForArrowFunction(parent) : parent; - jsDocNode.jsDoc = parent.jsDoc; - jsDocNode.jsDocCache = parent.jsDocCache; - changes.insertJsdocCommentBefore(sourceFile, jsDocNode, tag); - } - codefix.addJSDocTags = addJSDocTags; - function getJsDocNodeForArrowFunction(signature) { - if (signature.parent.kind === 166 /* PropertyDeclaration */) { - return signature.parent; - } - return signature.parent.parent; - } - function tryMergeJsdocTags(oldTag, newTag) { - if (oldTag.kind !== newTag.kind) { - return undefined; - } - switch (oldTag.kind) { - case 338 /* JSDocParameterTag */: { - var oldParam = oldTag; - var newParam = newTag; - return ts.isIdentifier(oldParam.name) && ts.isIdentifier(newParam.name) && oldParam.name.escapedText === newParam.name.escapedText - ? ts.factory.createJSDocParameterTag(/*tagName*/ undefined, newParam.name, /*isBracketed*/ false, newParam.typeExpression, newParam.isNameFirst, oldParam.comment) - : undefined; - } - case 339 /* JSDocReturnTag */: - return ts.factory.createJSDocReturnTag(/*tagName*/ undefined, newTag.typeExpression, oldTag.comment); + changes.addJSDocTags(sourceFile, signature, paramTags); } } function getReferences(token, program, cancellationToken) { @@ -152882,10 +154611,22 @@ var ts; if (usage.numberIndex) { types.push(checker.createArrayType(combineFromUsage(usage.numberIndex))); } - if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.calls) === null || _b === void 0 ? void 0 : _b.length) || ((_c = usage.constructs) === null || _c === void 0 ? void 0 : _c.length) || usage.stringIndex) { + if (((_a = usage.properties) === null || _a === void 0 ? void 0 : _a.size) || ((_b = usage.constructs) === null || _b === void 0 ? void 0 : _b.length) || usage.stringIndex) { types.push(inferStructuralType(usage)); } - types.push.apply(types, (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); })); + var candidateTypes = (usage.candidateTypes || []).map(function (t) { return checker.getBaseTypeOfLiteralType(t); }); + var callsType = ((_c = usage.calls) === null || _c === void 0 ? void 0 : _c.length) ? inferStructuralType(usage) : undefined; + if (callsType && candidateTypes) { + types.push(checker.getUnionType(__spreadArray([callsType], candidateTypes, true), 2 /* Subtype */)); + } + else { + if (callsType) { + types.push(callsType); + } + if (ts.length(candidateTypes)) { + types.push.apply(types, candidateTypes); + } + } types.push.apply(types, inferNamedTypesFromProperties(usage)); return types; } @@ -153046,7 +154787,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixId], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span; var checker = program.getTypeChecker(); var info = getInfo(sourceFile, program.getTypeChecker(), span.start); @@ -153100,7 +154841,7 @@ var ts; }); codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { var sourceFile = context.sourceFile, program = context.program, span = context.span, host = context.host, formatContext = context.formatContext; if (!ts.isInJSFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; @@ -153869,36 +155610,35 @@ var ts; var errorCodes = [ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { - var propertyDeclaration = getPropertyDeclaration(context.sourceFile, context.span.start); - if (!propertyDeclaration) + getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { + var info = getInfo(context.sourceFile, context.span.start); + if (!info) return; - var result = [ - getActionForAddMissingUndefinedType(context, propertyDeclaration), - getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) - ]; - ts.append(result, getActionForAddMissingInitializer(context, propertyDeclaration)); + var result = []; + ts.append(result, getActionForAddMissingUndefinedType(context, info)); + ts.append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); + ts.append(result, getActionForAddMissingInitializer(context, info)); return result; }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { - var propertyDeclaration = getPropertyDeclaration(diag.file, diag.start); - if (!propertyDeclaration) + var info = getInfo(diag.file, diag.start); + if (!info) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: - addDefiniteAssignmentAssertion(changes, diag.file, propertyDeclaration); + addDefiniteAssignmentAssertion(changes, diag.file, info.prop); break; case fixIdAddUndefinedType: - addUndefinedType(changes, diag.file, propertyDeclaration); + addUndefinedType(changes, diag.file, info); break; case fixIdAddInitializer: var checker = context.program.getTypeChecker(); - var initializer = getInitializer(checker, propertyDeclaration); + var initializer = getInitializer(checker, info.prop); if (!initializer) return; - addInitializer(changes, diag.file, propertyDeclaration, initializer); + addInitializer(changes, diag.file, info.prop, initializer); break; default: ts.Debug.fail(JSON.stringify(context.fixId)); @@ -153906,35 +155646,50 @@ var ts; }); }, }); - function getPropertyDeclaration(sourceFile, pos) { + function getInfo(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - return ts.isIdentifier(token) ? ts.cast(token.parent, ts.isPropertyDeclaration) : undefined; + if (ts.isIdentifier(token) && ts.isPropertyDeclaration(token.parent)) { + var type = ts.getEffectiveTypeAnnotationNode(token.parent); + if (type) { + return { type: type, prop: token.parent, isJs: ts.isInJSFile(token.parent) }; + } + } + return undefined; } - function getActionForAddMissingDefiniteAssignmentAssertion(context, propertyDeclaration) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, propertyDeclaration); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, propertyDeclaration.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); + function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { + if (info.isJs) + return undefined; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, ts.Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } function addDefiniteAssignmentAssertion(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, ts.factory.createToken(53 /* ExclamationToken */), propertyDeclaration.type, propertyDeclaration.initializer); changeTracker.replaceNode(propertyDeclarationSourceFile, propertyDeclaration, property); } - function getActionForAddMissingUndefinedType(context, propertyDeclaration) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, propertyDeclaration); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, propertyDeclaration.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); + function getActionForAddMissingUndefinedType(context, info) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addUndefinedType(t, context.sourceFile, info); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_undefined_type_to_property_0, info.prop.name.getText()], fixIdAddUndefinedType, ts.Diagnostics.Add_undefined_type_to_all_uninitialized_properties); } - function addUndefinedType(changeTracker, propertyDeclarationSourceFile, propertyDeclaration) { + function addUndefinedType(changeTracker, sourceFile, info) { var undefinedTypeNode = ts.factory.createKeywordTypeNode(152 /* UndefinedKeyword */); - var type = propertyDeclaration.type; // TODO: GH#18217 - var types = ts.isUnionTypeNode(type) ? type.types.concat(undefinedTypeNode) : [type, undefinedTypeNode]; - changeTracker.replaceNode(propertyDeclarationSourceFile, type, ts.factory.createUnionTypeNode(types)); + var types = ts.isUnionTypeNode(info.type) ? info.type.types.concat(undefinedTypeNode) : [info.type, undefinedTypeNode]; + var unionTypeNode = ts.factory.createUnionTypeNode(types); + if (info.isJs) { + changeTracker.addJSDocTags(sourceFile, info.prop, [ts.factory.createJSDocTypeTag(/*tagName*/ undefined, ts.factory.createJSDocTypeExpression(unionTypeNode))]); + } + else { + changeTracker.replaceNode(sourceFile, info.type, unionTypeNode); + } } - function getActionForAddMissingInitializer(context, propertyDeclaration) { + function getActionForAddMissingInitializer(context, info) { + if (info.isJs) + return undefined; var checker = context.program.getTypeChecker(); - var initializer = getInitializer(checker, propertyDeclaration); + var initializer = getInitializer(checker, info.prop); if (!initializer) return undefined; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, propertyDeclaration, initializer); }); - return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, propertyDeclaration.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addInitializer(t, context.sourceFile, info.prop, initializer); }); + return codefix.createCodeFixAction(fixName, changes, [ts.Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, ts.Diagnostics.Add_initializers_to_all_uninitialized_properties); } function addInitializer(changeTracker, propertyDeclarationSourceFile, propertyDeclaration, initializer) { var property = ts.factory.updatePropertyDeclaration(propertyDeclaration, propertyDeclaration.decorators, propertyDeclaration.modifiers, propertyDeclaration.name, propertyDeclaration.questionToken, propertyDeclaration.type, initializer); @@ -154092,7 +155847,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToUseBigintLiteral(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Convert_to_a_bigint_numeric_literal, fixId, ts.Diagnostics.Convert_all_to_bigint_numeric_literals)]; @@ -154124,7 +155879,7 @@ var ts; var errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToAddMissingTypeof(context) { var sourceFile = context.sourceFile, span = context.span; var importType = getImportTypeNode(sourceFile, span.start); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, importType); }); @@ -154156,7 +155911,7 @@ var ts; var errorCodes = [ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { var sourceFile = context.sourceFile, span = context.span; var node = findNodeToFix(sourceFile, span.start); if (!node) @@ -154228,12 +155983,11 @@ var ts; (function (ts) { var codefix; (function (codefix) { - var fixIdAddMissingTypeof = "fixConvertToMappedObjectType"; - var fixId = fixIdAddMissingTypeof; + var fixId = "fixConvertToMappedObjectType"; var errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { var sourceFile = context.sourceFile, span = context.span; var info = getInfo(sourceFile, span.start); if (!info) @@ -154251,10 +156005,12 @@ var ts; }); function getInfo(sourceFile, pos) { var token = ts.getTokenAtPosition(sourceFile, pos); - var indexSignature = ts.cast(token.parent.parent, ts.isIndexSignatureDeclaration); - if (ts.isClassDeclaration(indexSignature.parent)) + var indexSignature = ts.tryCast(token.parent.parent, ts.isIndexSignatureDeclaration); + if (!indexSignature) + return undefined; + var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.tryCast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); + if (!container) return undefined; - var container = ts.isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : ts.cast(indexSignature.parent.parent, ts.isTypeAliasDeclaration); return { indexSignature: indexSignature, container: container }; } function createTypeAliasFromInterface(declaration, type) { @@ -154312,7 +156068,7 @@ var ts; ]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span); }); if (changes.length > 0) { return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Remove_unnecessary_await, fixId, ts.Diagnostics.Remove_all_unnecessary_uses_of_await)]; @@ -154354,7 +156110,7 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, fixIds: [fixId], - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context); }); @@ -154390,7 +156146,7 @@ var ts; var errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; codefix.registerCodeFix({ errorCodes: errorCodes, - getCodeActions: function (context) { + getCodeActions: function getCodeActionsToConvertConstToLet(context) { var sourceFile = context.sourceFile, span = context.span, program = context.program; var range = getConstTokenRange(sourceFile, span.start, program); if (range === undefined) @@ -154561,7 +156317,7 @@ var ts; defaultToNamedAction.kind, namedToDefaultAction.kind ], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { var info = getInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -154579,7 +156335,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName) { ts.Debug.assert(actionName === defaultToNamedAction.name || actionName === namedToDefaultAction.name, "Unexpected action name"); var info = getInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); @@ -154791,51 +156547,53 @@ var ts; (function (ts) { var refactor; (function (refactor) { + var _a; var refactorName = "Convert import"; - var namespaceToNamedAction = { - name: "Convert namespace import to named imports", - description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named", - }; - var namedToNamespaceAction = { - name: "Convert named imports to namespace import", - description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace", - }; + var actions = (_a = {}, + _a[0 /* Named */] = { + name: "Convert namespace import to named imports", + description: ts.Diagnostics.Convert_namespace_import_to_named_imports.message, + kind: "refactor.rewrite.import.named", + }, + _a[2 /* Namespace */] = { + name: "Convert named imports to namespace import", + description: ts.Diagnostics.Convert_named_imports_to_namespace_import.message, + kind: "refactor.rewrite.import.namespace", + }, + _a[1 /* Default */] = { + name: "Convert named imports to default import", + description: ts.Diagnostics.Convert_named_imports_to_default_import.message, + kind: "refactor.rewrite.import.default", + }, + _a); refactor.registerRefactor(refactorName, { - kinds: [ - namespaceToNamedAction.kind, - namedToNamespaceAction.kind - ], - getAvailableActions: function (context) { - var info = getImportToConvert(context, context.triggerReason === "invoked"); + kinds: ts.getOwnValues(actions).map(function (a) { return a.kind; }), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + var info = getImportConversionInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; if (!refactor.isRefactorErrorInfo(info)) { - var namespaceImport = info.kind === 267 /* NamespaceImport */; - var action = namespaceImport ? namespaceToNamedAction : namedToNamespaceAction; + var action = actions[info.convertTo]; return [{ name: refactorName, description: action.description, actions: [action] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { name: refactorName, description: namespaceToNamedAction.description, - actions: [__assign(__assign({}, namespaceToNamedAction), { notApplicableReason: info.error })] }, - { name: refactorName, description: namedToNamespaceAction.description, - actions: [__assign(__assign({}, namedToNamespaceAction), { notApplicableReason: info.error })] } - ]; + return ts.getOwnValues(actions).map(function (action) { return ({ + name: refactorName, + description: action.description, + actions: [__assign(__assign({}, action), { notApplicableReason: info.error })] + }); }); } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { - ts.Debug.assert(actionName === namespaceToNamedAction.name || actionName === namedToNamespaceAction.name, "Unexpected action name"); - var info = getImportToConvert(context); + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName) { + ts.Debug.assert(ts.some(ts.getOwnValues(actions), function (action) { return action.name === actionName; }), "Unexpected action name"); + var info = getImportConversionInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, t, info); }); return { edits: edits, renameFilename: undefined, renameLocation: undefined }; } }); - // Can convert imports of the form `import * as m from "m";` or `import d, { x, y } from "m";`. - function getImportToConvert(context, considerPartialSpans) { + function getImportConversionInfo(context, considerPartialSpans) { if (considerPartialSpans === void 0) { considerPartialSpans = true; } var file = context.file; var span = ts.getRefactorContextSpan(context); @@ -154854,15 +156612,23 @@ var ts; if (!importClause.namedBindings) { return { error: ts.getLocaleSpecificMessage(ts.Diagnostics.Could_not_find_namespace_import_or_named_imports) }; } - return importClause.namedBindings; + if (importClause.namedBindings.kind === 267 /* NamespaceImport */) { + return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + } + var compilerOptions = context.program.getCompilerOptions(); + var shouldUseDefault = ts.getAllowSyntheticDefaultImports(compilerOptions) + && isExportEqualsModule(importClause.parent.moduleSpecifier, context.program.getTypeChecker()); + return shouldUseDefault + ? { convertTo: 1 /* Default */, import: importClause.namedBindings } + : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; } - function doChange(sourceFile, program, changes, toConvert) { + function doChange(sourceFile, program, changes, info) { var checker = program.getTypeChecker(); - if (toConvert.kind === 267 /* NamespaceImport */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); + if (info.convertTo === 0 /* Named */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())); } else { - doChangeNamedToNamespace(sourceFile, checker, changes, toConvert); + doChangeNamedToNamespaceOrDefault(sourceFile, checker, changes, info.import, info.convertTo === 1 /* Default */); } } function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { @@ -154912,7 +156678,7 @@ var ts; function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { return ts.isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; } - function doChangeNamedToNamespace(sourceFile, checker, changes, toConvert) { + function doChangeNamedToNamespaceOrDefault(sourceFile, checker, changes, toConvert, shouldUseDefault) { var importDecl = toConvert.parent.parent; var moduleSpecifier = importDecl.moduleSpecifier; var toConvertSymbols = new ts.Set(); @@ -154963,7 +156729,9 @@ var ts; var element = _a[_i]; _loop_17(element); } - changes.replaceNode(sourceFile, toConvert, ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); + changes.replaceNode(sourceFile, toConvert, shouldUseDefault + ? ts.factory.createIdentifier(namespaceImportName) + : ts.factory.createNamespaceImport(ts.factory.createIdentifier(namespaceImportName))); if (neededNamedImports.size) { var newNamedImports = ts.arrayFrom(neededNamedImports.values()).map(function (element) { return ts.factory.createImportSpecifier(element.isTypeOnly, element.propertyName && ts.factory.createIdentifier(element.propertyName.text), ts.factory.createIdentifier(element.name.text)); @@ -154971,6 +156739,13 @@ var ts; changes.insertNodeAfter(sourceFile, toConvert.parent.parent, updateImport(importDecl, /*defaultImportName*/ undefined, newNamedImports)); } } + function isExportEqualsModule(moduleSpecifier, checker) { + var externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) + return false; + var exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; + } function updateImport(old, defaultImportName, elements) { return ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } @@ -154992,10 +156767,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [toOptionalChainAction.kind], - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain, }); - function getAvailableActions(context) { + function getRefactorActionsToConvertToOptionalChain(context) { var info = getInfo(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -155015,7 +156790,7 @@ var ts; } return ts.emptyArray; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertToOptionalChain(context, actionName) { var info = getInfo(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { @@ -155258,10 +157033,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [functionOverloadAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature }); - function getAvailableActions(context) { + function getRefactorActionsToConvertOverloadsToOneSignature(context) { var file = context.file, startPosition = context.startPosition, program = context.program; var info = getConvertableOverloadListAtPosition(file, startPosition, program); if (!info) @@ -155272,7 +157047,7 @@ var ts; actions: [functionOverloadAction] }]; } - function getEditsForAction(context) { + function getRefactorEditsToConvertOverloadsToOneSignature(context) { var file = context.file, startPosition = context.startPosition, program = context.program; var signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); if (!signatureDecls) @@ -155428,14 +157203,14 @@ var ts; extractConstantAction.kind, extractFunctionAction.kind ], - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol, }); /** * Compute the associated code actions * Exported for tests. */ - function getAvailableActions(context) { + function getRefactorActionsToExtractSymbol(context) { var requestedRefactor = context.kind; var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context), context.triggerReason === "invoked"); var targetRange = rangeToExtract.targetRange; @@ -155564,9 +157339,9 @@ var ts; return error; } } - extractSymbol.getAvailableActions = getAvailableActions; + extractSymbol.getRefactorActionsToExtractSymbol = getRefactorActionsToExtractSymbol; /* Exported for tests */ - function getEditsForAction(context, actionName) { + function getRefactorEditsToExtractSymbol(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); var targetRange = rangeToExtract.targetRange; // TODO:GH#18217 var parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName); @@ -155583,7 +157358,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol.getEditsForAction = getEditsForAction; + extractSymbol.getRefactorEditsToExtractSymbol = getRefactorEditsToExtractSymbol; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -155658,7 +157433,7 @@ var ts; // cannot find either start or end node return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } - if (ts.isJSDoc(start)) { + if (start.flags & 4194304 /* JSDoc */) { return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractJSDoc)] }; } if (start.parent !== end.parent) { @@ -155671,8 +157446,7 @@ var ts; return { errors: [ts.createFileDiagnostic(sourceFile, span.start, length, Messages.cannotExtractRange)] }; } var statements = []; - var start2 = start; // TODO: GH#18217 Need to alias `start` to get this to compile. See https://github.com/Microsoft/TypeScript/issues/19955#issuecomment-344118248 - for (var _i = 0, _a = start2.parent.statements; _i < _a.length; _i++) { + for (var _i = 0, _a = start.parent.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement === start || statements.length) { var errors_1 = checkNode(statement); @@ -155716,11 +157490,12 @@ var ts; return node.expression; } } - else if (ts.isVariableStatement(node)) { + else if (ts.isVariableStatement(node) || ts.isVariableDeclarationList(node)) { + var declarations_5 = ts.isVariableStatement(node) ? node.declarationList.declarations : node.declarations; var numInitializers = 0; var lastInitializer = void 0; - for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { - var declaration = _a[_i]; + for (var _i = 0, declarations_4 = declarations_5; _i < declarations_4.length; _i++) { + var declaration = declarations_4[_i]; if (declaration.initializer) { numInitializers++; lastInitializer = declaration.initializer; @@ -155826,8 +157601,8 @@ var ts; // but a super *method call* simply implies a 'this' reference if (node.parent.kind === 207 /* CallExpression */) { // Super constructor call - var containingClass_1 = ts.getContainingClass(node); // TODO:GH#18217 - if (containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { + var containingClass_1 = ts.getContainingClass(node); + if (containingClass_1 === undefined || containingClass_1.pos < span.start || containingClass_1.end >= (span.start + span.length)) { (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractSuper)); return true; } @@ -157134,7 +158909,7 @@ var ts; extractToInterfaceAction.kind, extractToTypeDefAction.kind ], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToExtractType(context) { var info = getRangeToExtract(context, context.triggerReason === "invoked"); if (!info) return ts.emptyArray; @@ -157159,7 +158934,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToExtractType(context, actionName) { var file = context.file; var info = getRangeToExtract(context); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected to find a range to extract"); @@ -157236,11 +159011,20 @@ var ts; function visitor(node) { if (ts.isTypeReferenceNode(node)) { if (ts.isIdentifier(node.typeName)) { - var symbol = checker.resolveName(node.typeName.text, node.typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); - if (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) { - var declaration = ts.cast(ts.first(symbol.declarations), ts.isTypeParameterDeclaration); - if (rangeContainsSkipTrivia(statement, declaration, file) && !rangeContainsSkipTrivia(selection, declaration, file)) { - ts.pushIfUnique(result, declaration); + var typeName = node.typeName; + var symbol = checker.resolveName(typeName.text, typeName, 262144 /* TypeParameter */, /* excludeGlobals */ true); + for (var _i = 0, _a = (symbol === null || symbol === void 0 ? void 0 : symbol.declarations) || ts.emptyArray; _i < _a.length; _i++) { + var decl = _a[_i]; + if (ts.isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + // skip extraction if the type node is in the range of the type parameter declaration. + // function foo<T extends { a?: /**/T }>(): void; + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + return true; + } + if (rangeContainsSkipTrivia(statement, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + ts.pushIfUnique(result, decl); + break; + } } } } @@ -157326,7 +159110,7 @@ var ts; }; refactor.registerRefactor(actionName, { kinds: [generateGetSetAction.kind], - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName) { if (!context.endPosition) return undefined; var info = ts.codefix.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); @@ -157405,7 +159189,7 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [moveToNewFileAction.kind], - getAvailableActions: function (context) { + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { var statements = getStatementsToMove(context); if (context.preferences.allowTextChangesInNewFiles && statements) { return [{ name: refactorName, description: description, actions: [moveToNewFileAction] }]; @@ -157416,7 +159200,7 @@ var ts; } return ts.emptyArray; }, - getEditsForAction: function (context, actionName) { + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName) { ts.Debug.assert(actionName === refactorName, "Wrong refactor invoked"); var statements = ts.Debug.checkDefined(getStatementsToMove(context)); var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, context.program, statements, t, context.host, context.preferences); }); @@ -158147,10 +159931,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [removeBracesAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces }); - function getAvailableActions(context) { + function getRefactorActionsToRemoveFunctionBraces(context) { var file = context.file, startPosition = context.startPosition, triggerReason = context.triggerReason; var info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); if (!info) @@ -158176,7 +159960,7 @@ var ts; } return ts.emptyArray; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToRemoveFunctionBraces(context, actionName) { var file = context.file, startPosition = context.startPosition; var info = getConvertibleArrowFunctionAtPosition(file, startPosition); ts.Debug.assert(info && !refactor.isRefactorErrorInfo(info), "Expected applicable refactor info"); @@ -158241,7 +160025,7 @@ var ts; var convertParamsToDestructuredObject; (function (convertParamsToDestructuredObject) { var refactorName = "Convert parameters to destructured object"; - var minimumParameterLength = 2; + var minimumParameterLength = 1; var refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object); var toDestructuredAction = { name: refactorName, @@ -158250,10 +160034,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [toDestructuredAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject }); - function getAvailableActions(context) { + function getRefactorActionsToConvertParametersToDestructuredObject(context) { var file = context.file, startPosition = context.startPosition; var isJSFile = ts.isSourceFileJS(file); if (isJSFile) @@ -158267,7 +160051,7 @@ var ts; actions: [toDestructuredAction] }]; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName) { ts.Debug.assert(actionName === refactorName, "Unexpected action name"); var file = context.file, startPosition = context.startPosition, program = context.program, cancellationToken = context.cancellationToken, host = context.host; var functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); @@ -158777,10 +160561,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [convertStringAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString }); - function getAvailableActions(context) { + function getRefactorActionsToConvertToTemplateString(context) { var file = context.file, startPosition = context.startPosition; var node = getNodeOrParentOfParentheses(file, startPosition); var maybeBinary = getParentBinaryExpression(node); @@ -158806,7 +160590,7 @@ var ts; } return node; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertToTemplateString(context, actionName) { var file = context.file, startPosition = context.startPosition; var node = getNodeOrParentOfParentheses(file, startPosition); switch (actionName) { @@ -159020,10 +160804,10 @@ var ts; toNamedFunctionAction.kind, toArrowFunctionAction.kind ], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions }); - function getAvailableActions(context) { + function getRefactorActionsToConvertFunctionExpressions(context) { var file = context.file, startPosition = context.startPosition, program = context.program, kind = context.kind; var info = getFunctionInfo(file, startPosition, program); if (!info) @@ -159067,7 +160851,7 @@ var ts; errors : possibleActions }]; } - function getEditsForAction(context, actionName) { + function getRefactorEditsToConvertFunctionExpressions(context, actionName) { var file = context.file, startPosition = context.startPosition, program = context.program; var info = getFunctionInfo(file, startPosition, program); if (!info) @@ -159227,10 +161011,10 @@ var ts; }; refactor.registerRefactor(refactorName, { kinds: [inferReturnTypeAction.kind], - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType }); - function getEditsForAction(context) { + function getRefactorEditsToInferReturnType(context) { var info = getInfo(context); if (info && !refactor.isRefactorErrorInfo(info)) { var edits = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(context.file, t, info.declaration, info.returnTypeNode); }); @@ -159238,7 +161022,7 @@ var ts; } return undefined; } - function getAvailableActions(context) { + function getRefactorActionsToInferReturnType(context) { var info = getInfo(context); if (!info) return ts.emptyArray; @@ -159583,13 +161367,11 @@ var ts; switch (context === null || context === void 0 ? void 0 : context.kind) { case 171 /* GetAccessor */: if (!this.contextualGetAccessorDocumentationComment) { - this.contextualGetAccessorDocumentationComment = ts.emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isGetAccessor), checker); } return this.contextualGetAccessorDocumentationComment; case 172 /* SetAccessor */: if (!this.contextualSetAccessorDocumentationComment) { - this.contextualSetAccessorDocumentationComment = ts.emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(ts.filter(this.declarations, ts.isSetAccessor), checker); } return this.contextualSetAccessorDocumentationComment; @@ -159599,10 +161381,26 @@ var ts; }; SymbolObject.prototype.getJsDocTags = function (checker) { if (this.tags === undefined) { - this.tags = ts.JsDoc.getJsDocTagsFromDeclarations(this.declarations, checker); + this.tags = getJsDocTagsOfDeclarations(this.declarations, checker); } return this.tags; }; + SymbolObject.prototype.getContextualJsDocTags = function (context, checker) { + switch (context === null || context === void 0 ? void 0 : context.kind) { + case 171 /* GetAccessor */: + if (!this.contextualGetAccessorTags) { + this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isGetAccessor), checker); + } + return this.contextualGetAccessorTags; + case 172 /* SetAccessor */: + if (!this.contextualSetAccessorTags) { + this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(ts.filter(this.declarations, ts.isSetAccessor), checker); + } + return this.contextualSetAccessorTags; + default: + return this.getJsDocTags(checker); + } + }; return SymbolObject; }()); var TokenObject = /** @class */ (function (_super) { @@ -159723,6 +161521,9 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + TypeObject.prototype.isIndexType = function () { + return !!(this.flags & 4194304 /* Index */); + }; Object.defineProperty(TypeObject.prototype, "typeArguments", { /** * This polyfills `referenceType.typeArguments` for API consumers @@ -159755,14 +161556,21 @@ var ts; SignatureObject.prototype.getReturnType = function () { return this.checker.getReturnTypeOfSignature(this); }; + SignatureObject.prototype.getTypeParameterAtPosition = function (pos) { + var type = this.checker.getParameterType(this, pos); + if (type.isIndexType() && ts.isThisTypeParameter(type.type)) { + var constraint = type.type.getConstraint(); + if (constraint) { + return this.checker.getIndexType(constraint); + } + } + return type; + }; SignatureObject.prototype.getDocumentationComment = function () { return this.documentationComment || (this.documentationComment = getDocumentationComment(ts.singleElementArray(this.declaration), this.checker)); }; SignatureObject.prototype.getJsDocTags = function () { - if (this.jsDocTags === undefined) { - this.jsDocTags = this.declaration ? getJsDocTagsOfSignature(this.declaration, this.checker) : []; - } - return this.jsDocTags; + return this.jsDocTags || (this.jsDocTags = getJsDocTagsOfDeclarations(ts.singleElementArray(this.declaration), this.checker)); }; return SignatureObject; }()); @@ -159774,12 +161582,30 @@ var ts; function hasJSDocInheritDocTag(node) { return ts.getJSDocTags(node).some(function (tag) { return tag.tagName.text === "inheritDoc"; }); } - function getJsDocTagsOfSignature(declaration, checker) { - var tags = ts.JsDoc.getJsDocTagsFromDeclarations([declaration], checker); - if (tags.length === 0 || hasJSDocInheritDocTag(declaration)) { - var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { var _a; return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; }); - if (inheritedTags) { - tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); + function getJsDocTagsOfDeclarations(declarations, checker) { + if (!declarations) + return ts.emptyArray; + var tags = ts.JsDoc.getJsDocTagsFromDeclarations(declarations, checker); + if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { + var seenSymbols_1 = new ts.Set(); + var _loop_22 = function (declaration) { + var inheritedTags = findBaseOfDeclaration(checker, declaration, function (symbol) { + var _a; + if (!seenSymbols_1.has(symbol)) { + seenSymbols_1.add(symbol); + if (declaration.kind === 171 /* GetAccessor */ || declaration.kind === 172 /* SetAccessor */) { + return symbol.getContextualJsDocTags(declaration, checker); + } + return ((_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a.length) === 1 ? symbol.getJsDocTags() : undefined; + } + }); + if (inheritedTags) { + tags = __spreadArray(__spreadArray([], inheritedTags, true), tags, true); + } + }; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; + _loop_22(declaration); } } return tags; @@ -159789,28 +161615,35 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { - var seenSymbols_1 = new ts.Set(); - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + var seenSymbols_2 = new ts.Set(); + var _loop_23 = function (declaration) { var inheritedDocs = findBaseOfDeclaration(checker, declaration, function (symbol) { - if (!seenSymbols_1.has(symbol)) { - seenSymbols_1.add(symbol); + if (!seenSymbols_2.has(symbol)) { + seenSymbols_2.add(symbol); + if (declaration.kind === 171 /* GetAccessor */ || declaration.kind === 172 /* SetAccessor */) { + return symbol.getContextualDocumentationComment(declaration, checker); + } return symbol.getDocumentationComment(checker); } }); // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); + }; + for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) { + var declaration = declarations_7[_i]; + _loop_23(declaration); } } return doc; } function findBaseOfDeclaration(checker, declaration, cb) { var _a; + if (ts.hasStaticModifier(declaration)) + return; var classOrInterfaceDeclaration = ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.kind) === 170 /* Constructor */ ? declaration.parent.parent : declaration.parent; - if (!classOrInterfaceDeclaration) { + if (!classOrInterfaceDeclaration) return; - } return ts.firstDefined(ts.getAllSuperTypeNodes(classOrInterfaceDeclaration), function (superTypeNode) { var symbol = checker.getPropertyOfType(checker.getTypeAtLocation(superTypeNode), declaration.symbol.name); return symbol ? cb(symbol) : undefined; @@ -160297,6 +162130,7 @@ var ts; ], false); function createLanguageService(host, documentRegistry, syntaxOnlyOrLanguageServiceMode) { var _a; + var _b; if (documentRegistry === void 0) { documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var languageServiceMode; if (syntaxOnlyOrLanguageServiceMode === undefined) { @@ -160317,10 +162151,8 @@ var ts; ? new CancellationTokenObject(host.getCancellationToken()) : NoopCancellationToken; var currentDirectory = host.getCurrentDirectory(); - // Check if the localized messages json is set, otherwise query the host for it - if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { - ts.setLocalizedDiagnosticMessages(host.getLocalizedDiagnosticMessages()); - } + // Checks if the localized messages json is set, and if not, query the host for it + ts.maybeSetLocalizedDiagnosticMessages((_b = host.getLocalizedDiagnosticMessages) === null || _b === void 0 ? void 0 : _b.bind(host)); function log(message) { if (host.log) { host.log(message); @@ -160422,6 +162254,7 @@ var ts; hasChangedAutomaticTypeDirectiveNames: hasChangedAutomaticTypeDirectiveNames, trace: parseConfigHost.trace, resolveModuleNames: ts.maybeBind(host, host.resolveModuleNames), + getModuleResolutionCache: ts.maybeBind(host, host.getModuleResolutionCache), resolveTypeReferenceDirectives: ts.maybeBind(host, host.resolveTypeReferenceDirectives), useSourceOfProjectReferenceRedirect: ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine: getParsedCommandLine, @@ -160618,12 +162451,12 @@ var ts; synchronizeHostData(); return __spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken), true), program.getGlobalDiagnostics(cancellationToken), true); } - function getCompletionsAtPosition(fileName, position, options) { + function getCompletionsAtPosition(fileName, position, options, formattingSettings) { if (options === void 0) { options = ts.emptyOptions; } // Convert from deprecated options names to new names var fullPreferences = __assign(__assign({}, ts.identity(options)), { includeCompletionsForModuleExports: options.includeCompletionsForModuleExports || options.includeExternalModuleExports, includeCompletionsWithInsertText: options.includeCompletionsWithInsertText || options.includeInsertTextCompletions }); synchronizeHostData(); - return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken); + return ts.Completions.getCompletionsAtPosition(host, program, log, getValidSourceFile(fileName), position, fullPreferences, options.triggerCharacter, options.triggerKind, cancellationToken, formattingSettings && ts.formatting.getFormatContext(formattingSettings, host)); } function getCompletionEntryDetails(fileName, position, name, formattingOptions, source, preferences, data) { if (preferences === void 0) { preferences = ts.emptyOptions; } @@ -162786,9 +164619,9 @@ var ts; * to provide at the given source position and providing a member completion * list if requested. */ - LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences) { + LanguageServiceShimObject.prototype.getCompletionsAtPosition = function (fileName, position, preferences, formattingSettings) { var _this = this; - return this.forwardJSONCall("getCompletionsAtPosition('".concat(fileName, "', ").concat(position, ", ").concat(preferences, ")"), function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences); }); + return this.forwardJSONCall("getCompletionsAtPosition('".concat(fileName, "', ").concat(position, ", ").concat(preferences, ", ").concat(formattingSettings, ")"), function () { return _this.languageService.getCompletionsAtPosition(fileName, position, preferences, formattingSettings); }); }; /** Get a string based representation of a completion list entry details */ LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, formatOptions, source, preferences, data) { |