diff --git a/lib/lib.esnext.collection.d.ts b/lib/lib.esnext.collection.d.ts index a48fd93d5f806..1278a38f67a34 100644 --- a/lib/lib.esnext.collection.d.ts +++ b/lib/lib.esnext.collection.d.ts @@ -27,3 +27,80 @@ interface MapConstructor { keySelector: (item: T, index: number) => K, ): Map; } + +interface ReadonlySetLike { + /** + * Despite its name, returns an iterator of the values in the set-like. + */ + keys(): Iterator; + /** + * @returns a boolean indicating whether an element with the specified value exists in the set-like or not. + */ + has(value: T): boolean; + /** + * @returns the number of (unique) elements in the set-like. + */ + readonly size: number; +} + +interface Set { + /** + * @returns a new Set containing all the elements in this Set and also all the elements in the argument. + */ + union(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements which are both in this Set and in the argument. + */ + intersection(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements in this Set which are not also in the argument. + */ + difference(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements which are in either this Set or in the argument, but not in both. + */ + symmetricDifference(other: ReadonlySetLike): Set; + /** + * @returns a boolean indicating whether all the elements in this Set are also in the argument. + */ + isSubsetOf(other: ReadonlySetLike): boolean; + /** + * @returns a boolean indicating whether all the elements in the argument are also in this Set. + */ + isSupersetOf(other: ReadonlySetLike): boolean; + /** + * @returns a boolean indicating whether this Set has no elements in common with the argument. + */ + isDisjointFrom(other: ReadonlySetLike): boolean; +} + +interface ReadonlySet { + /** + * @returns a new Set containing all the elements in this Set and also all the elements in the argument. + */ + union(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements which are both in this Set and in the argument. + */ + intersection(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements in this Set which are not also in the argument. + */ + difference(other: ReadonlySetLike): Set; + /** + * @returns a new Set containing all the elements which are in either this Set or in the argument, but not in both. + */ + symmetricDifference(other: ReadonlySetLike): Set; + /** + * @returns a boolean indicating whether all the elements in this Set are also in the argument. + */ + isSubsetOf(other: ReadonlySetLike): boolean; + /** + * @returns a boolean indicating whether all the elements in the argument are also in this Set. + */ + isSupersetOf(other: ReadonlySetLike): boolean; + /** + * @returns a boolean indicating whether this Set has no elements in common with the argument. + */ + isDisjointFrom(other: ReadonlySetLike): boolean; +} diff --git a/lib/tsc.js b/lib/tsc.js index 06f7f5ec973cc..f8775a74c7fcd 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -88,8 +88,7 @@ function every(array, callback) { return true; } function find(array, predicate, startIndex) { - if (array === void 0) - return void 0; + if (array === void 0) return void 0; for (let i = startIndex ?? 0; i < array.length; i++) { const value = array[i]; if (predicate(value, i)) { @@ -99,8 +98,7 @@ function find(array, predicate, startIndex) { return void 0; } function findLast(array, predicate, startIndex) { - if (array === void 0) - return void 0; + if (array === void 0) return void 0; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { const value = array[i]; if (predicate(value, i)) { @@ -110,8 +108,7 @@ function findLast(array, predicate, startIndex) { return void 0; } function findIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; + if (array === void 0) return -1; for (let i = startIndex ?? 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; @@ -120,8 +117,7 @@ function findIndex(array, predicate, startIndex) { return -1; } function findLastIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; + if (array === void 0) return -1; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; @@ -166,8 +162,7 @@ function filter(array, f) { if (array) { const len = array.length; let i = 0; - while (i < len && f(array[i])) - i++; + while (i < len && f(array[i])) i++; if (i < len) { const result = array.slice(0, i); i++; @@ -387,14 +382,11 @@ function getRangesWhere(arr, pred, cb) { } } } - if (start !== void 0) - cb(start, arr.length); + if (start !== void 0) cb(start, arr.length); } function concatenate(array1, array2) { - if (!some(array2)) - return array1; - if (!some(array1)) - return array2; + if (!some(array2)) return array1; + if (!some(array1)) return array2; return [...array1, ...array2]; } function selectIndex(_, i) { @@ -430,8 +422,7 @@ function deduplicate(array, equalityComparer, comparer) { return array.length === 0 ? [] : array.length === 1 ? array.slice() : comparer ? deduplicateRelational(array, equalityComparer, comparer) : deduplicateEquality(array, equalityComparer); } function deduplicateSorted(array, comparer) { - if (array.length === 0) - return emptyArray; + if (array.length === 0) return emptyArray; let last2 = array[0]; const deduplicated = [last2]; for (let i = 1; i < array.length; i++) { @@ -447,13 +438,23 @@ function deduplicateSorted(array, comparer) { } return deduplicated; } -function insertSorted(array, insert, compare, allowDuplicates) { +function insertSorted(array, insert, compare, equalityComparer, allowDuplicates) { if (array.length === 0) { array.push(insert); return true; } const insertIndex = binarySearch(array, insert, identity, compare); if (insertIndex < 0) { + if (equalityComparer && !allowDuplicates) { + const idx = ~insertIndex; + if (idx > 0 && equalityComparer(insert, array[idx - 1])) { + return false; + } + if (idx < array.length && equalityComparer(insert, array[idx])) { + array.splice(idx, 1, insert); + return true; + } + } array.splice(~insertIndex, 0, insert); return true; } @@ -498,8 +499,7 @@ function compact(array) { return result || array; } function relativeComplement(arrayA, arrayB, comparer) { - if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) - return arrayB; + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; const result = []; loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { @@ -525,10 +525,8 @@ function relativeComplement(arrayA, arrayB, comparer) { return result; } function append(to, value) { - if (value === void 0) - return to; - if (to === void 0) - return [value]; + if (value === void 0) return to; + if (to === void 0) return [value]; to.push(value); return to; } @@ -536,10 +534,8 @@ function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } function addRange(to, from, start, end) { - if (from === void 0 || from.length === 0) - return to; - if (to === void 0) - return from.slice(start, end); + if (from === void 0 || from.length === 0) return to; + if (to === void 0) return from.slice(start, end); start = start === void 0 ? 0 : toOffset(from, start); end = end === void 0 ? from.length : toOffset(from, end); for (let i = start; i < end && i < from.length; i++) { @@ -718,8 +714,7 @@ function arrayFrom(iterator, map2) { } function assign(t, ...args) { for (const arg of args) { - if (arg === void 0) - continue; + if (arg === void 0) continue; for (const p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; @@ -729,22 +724,17 @@ function assign(t, ...args) { return t; } function equalOwnProperties(left, right, equalityComparer = equateValues) { - if (left === right) - return true; - if (!left || !right) - return false; + if (left === right) return true; + if (!left || !right) return false; for (const key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key)) - return false; - if (!equalityComparer(left[key], right[key])) - return false; + if (!hasOwnProperty.call(right, key)) return false; + if (!equalityComparer(left[key], right[key])) return false; } } for (const key in right) { if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; + if (!hasOwnProperty.call(left, key)) return false; } } return true; @@ -753,8 +743,7 @@ function arrayToMap(array, makeKey, makeValue = identity) { const result = /* @__PURE__ */ new Map(); for (const value of array) { const key = makeKey(value); - if (key !== void 0) - result.set(key, makeValue(value)); + if (key !== void 0) result.set(key, makeValue(value)); } return result; } @@ -878,8 +867,7 @@ function tryCast(value, test) { return value !== void 0 && test(value) ? value : void 0; } function cast(value, test) { - if (value !== void 0 && test(value)) - return value; + if (value !== void 0 && test(value)) return value; return Debug.fail(`Invalid cast. The supplied value ${value} did not pass the test '${Debug.getFunctionName(test)}'.`); } function noop(_) { @@ -947,12 +935,9 @@ function min(items, compare) { return reduceLeft(items, (x, y) => compare(x, y) === -1 /* LessThan */ ? x : y); } function compareStringsCaseInsensitive(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; a = a.toUpperCase(); b = b.toUpperCase(); return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; @@ -1533,6 +1518,15 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, ); } Debug2.formatNodeFlags = formatNodeFlags; + function formatNodeCheckFlags(flags) { + return formatEnum( + flags, + NodeCheckFlags, + /*isFlags*/ + true + ); + } + Debug2.formatNodeCheckFlags = formatNodeCheckFlags; function formatModifierFlags(flags) { return formatEnum( flags, @@ -1715,8 +1709,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } Debug2.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo; function enableDebugInfo() { - if (isDebugInfoEnabled) - return; + if (isDebugInfoEnabled) return; const weakTypeTextMap = /* @__PURE__ */ new WeakMap(); const weakNodeTextMap = /* @__PURE__ */ new WeakMap(); Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, { @@ -1825,8 +1818,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, }, __debugGetText: { value(includeTrivia) { - if (nodeIsSynthesized(this)) - return ""; + if (nodeIsSynthesized(this)) return ""; let text = weakNodeTextMap.get(this); if (text === void 0) { const parseNode = getParseTreeNode(this); @@ -2056,8 +2048,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; node.endLane = lane; const children = getChildren(node); for (let i = 0; i < children.length; i++) { - if (i > 0) - lane++; + if (i > 0) lane++; const child = children[i]; computeLanes(child, lane); if (child.endLane > node.endLane) { @@ -2068,28 +2059,17 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } } function getHeader2(flags) { - if (flags & 2 /* Start */) - return "Start"; - if (flags & 4 /* BranchLabel */) - return "Branch"; - if (flags & 8 /* LoopLabel */) - return "Loop"; - if (flags & 16 /* Assignment */) - return "Assignment"; - if (flags & 32 /* TrueCondition */) - return "True"; - if (flags & 64 /* FalseCondition */) - return "False"; - if (flags & 128 /* SwitchClause */) - return "SwitchClause"; - if (flags & 256 /* ArrayMutation */) - return "ArrayMutation"; - if (flags & 512 /* Call */) - return "Call"; - if (flags & 1024 /* ReduceLabel */) - return "ReduceLabel"; - if (flags & 1 /* Unreachable */) - return "Unreachable"; + if (flags & 2 /* Start */) return "Start"; + if (flags & 4 /* BranchLabel */) return "Branch"; + if (flags & 8 /* LoopLabel */) return "Loop"; + if (flags & 16 /* Assignment */) return "Assignment"; + if (flags & 32 /* TrueCondition */) return "True"; + if (flags & 64 /* FalseCondition */) return "False"; + if (flags & 128 /* SwitchClause */) return "SwitchClause"; + if (flags & 256 /* ArrayMutation */) return "ArrayMutation"; + if (flags & 512 /* Call */) return "Call"; + if (flags & 1024 /* ReduceLabel */) return "ReduceLabel"; + if (flags & 1 /* Unreachable */) return "Unreachable"; throw new Error(); } function getNodeText(node) { @@ -2137,12 +2117,9 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; for (let i = 0; i < children.length; i++) { const child = children[i]; let connector = 8 /* Right */; - if (child.lane === node.lane) - connector |= 4 /* Left */; - if (i > 0) - connector |= 1 /* Up */; - if (i < children.length - 1) - connector |= 2 /* Down */; + if (child.lane === node.lane) connector |= 4 /* Left */; + if (i > 0) connector |= 1 /* Up */; + if (i < children.length - 1) connector |= 2 /* Down */; connectors[node.level][child.lane] |= connector; } if (children.length === 0) { @@ -2152,10 +2129,8 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; for (let i = 0; i < parents.length; i++) { const parent = parents[i]; let connector = 4 /* Left */; - if (i > 0) - connector |= 1 /* Up */; - if (i < parents.length - 1) - connector |= 2 /* Down */; + if (i > 0) connector |= 1 /* Up */; + if (i < parents.length - 1) connector |= 2 /* Down */; connectors[node.level - 1][parent.lane] |= connector; } } @@ -2165,10 +2140,8 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; const above = lane > 0 ? connectors[column][lane - 1] : 0; let connector = connectors[column][lane]; if (!connector) { - if (left & 8 /* Right */) - connector |= 12 /* LeftRight */; - if (above & 2 /* Down */) - connector |= 3 /* UpDown */; + if (left & 8 /* Right */) connector |= 12 /* LeftRight */; + if (above & 2 /* Down */) connector |= 3 /* UpDown */; connectors[column][lane] = connector; } } @@ -2279,16 +2252,13 @@ var _Version = class _Version { } static tryParse(text) { const result = tryParseComponents(text); - if (!result) - return void 0; + if (!result) return void 0; const { major, minor, patch, prerelease, build: build2 } = result; return new _Version(major, minor, patch, prerelease, build2); } compareTo(other) { - if (this === other) - return 0 /* EqualTo */; - if (other === void 0) - return 1 /* GreaterThan */; + if (this === other) return 0 /* EqualTo */; + if (other === void 0) return 1 /* GreaterThan */; return compareValues(this.major, other.major) || compareValues(this.minor, other.minor) || compareValues(this.patch, other.patch) || comparePrereleaseIdentifiers(this.prerelease, other.prerelease); } increment(field) { @@ -2315,10 +2285,8 @@ var _Version = class _Version { } toString() { let result = `${this.major}.${this.minor}.${this.patch}`; - if (some(this.prerelease)) - result += `-${this.prerelease.join(".")}`; - if (some(this.build)) - result += `+${this.build.join(".")}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; return result; } }; @@ -2326,13 +2294,10 @@ _Version.zero = new _Version(0, 0, 0, ["0"]); var Version = _Version; function tryParseComponents(text) { const match = versionRegExp.exec(text); - if (!match) - return void 0; + if (!match) return void 0; const [, major, minor = "0", patch = "0", prerelease = "", build2 = ""] = match; - if (prerelease && !prereleaseRegExp.test(prerelease)) - return void 0; - if (build2 && !buildRegExp.test(build2)) - return void 0; + if (prerelease && !prereleaseRegExp.test(prerelease)) return void 0; + if (build2 && !buildRegExp.test(build2)) return void 0; return { major: parseInt(major, 10), minor: parseInt(minor, 10), @@ -2342,30 +2307,23 @@ function tryParseComponents(text) { }; } function comparePrereleaseIdentifiers(left, right) { - if (left === right) - return 0 /* EqualTo */; - if (left.length === 0) - return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; - if (right.length === 0) - return -1 /* LessThan */; + if (left === right) return 0 /* EqualTo */; + if (left.length === 0) return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) return -1 /* LessThan */; const length2 = Math.min(left.length, right.length); for (let i = 0; i < length2; i++) { const leftIdentifier = left[i]; const rightIdentifier = right[i]; - if (leftIdentifier === rightIdentifier) - continue; + if (leftIdentifier === rightIdentifier) continue; const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); if (leftIsNumeric || rightIsNumeric) { - if (leftIsNumeric !== rightIsNumeric) - return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; const result = compareValues(+leftIdentifier, +rightIdentifier); - if (result) - return result; + if (result) return result; } else { const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); - if (result) - return result; + if (result) return result; } } return compareValues(left.length, right.length); @@ -2388,8 +2346,7 @@ var VersionRange = class _VersionRange { * in `node-semver`. */ test(version2) { - if (typeof version2 === "string") - version2 = new Version(version2); + if (typeof version2 === "string") version2 = new Version(version2); return testDisjunction(version2, this._alternatives); } toString() { @@ -2404,19 +2361,16 @@ var rangeRegExp = /^(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; function parseRange(text) { const alternatives = []; for (let range of text.trim().split(logicalOrRegExp)) { - if (!range) - continue; + if (!range) continue; const comparators = []; range = range.trim(); const match = hyphenRegExp.exec(range); if (match) { - if (!parseHyphen(match[1], match[2], comparators)) - return void 0; + if (!parseHyphen(match[1], match[2], comparators)) return void 0; } else { for (const simple of range.split(whitespaceRegExp)) { const match2 = rangeRegExp.exec(simple.trim()); - if (!match2 || !parseComparator(match2[1], match2[2], comparators)) - return void 0; + if (!match2 || !parseComparator(match2[1], match2[2], comparators)) return void 0; } } alternatives.push(comparators); @@ -2425,8 +2379,7 @@ function parseRange(text) { } function parsePartial(text) { const match = partialRegExp.exec(text); - if (!match) - return void 0; + if (!match) return void 0; const [, major, minor = "*", patch = "*", prerelease, build2] = match; const version2 = new Version( isWildcard(major) ? 0 : parseInt(major, 10), @@ -2439,11 +2392,9 @@ function parsePartial(text) { } function parseHyphen(left, right, comparators) { const leftResult = parsePartial(left); - if (!leftResult) - return false; + if (!leftResult) return false; const rightResult = parsePartial(right); - if (!rightResult) - return false; + if (!rightResult) return false; if (!isWildcard(leftResult.major)) { comparators.push(createComparator(">=", leftResult.version)); } @@ -2456,8 +2407,7 @@ function parseHyphen(left, right, comparators) { } function parseComparator(operator, text, comparators) { const result = parsePartial(text); - if (!result) - return false; + if (!result) return false; const { version: version2, major, minor, patch } = result; if (!isWildcard(major)) { switch (operator) { @@ -2515,18 +2465,15 @@ function createComparator(operator, operand) { return { operator, operand }; } function testDisjunction(version2, alternatives) { - if (alternatives.length === 0) - return true; + if (alternatives.length === 0) return true; for (const alternative of alternatives) { - if (testAlternative(version2, alternative)) - return true; + if (testAlternative(version2, alternative)) return true; } return false; } function testAlternative(version2, comparators) { for (const comparator of comparators) { - if (!testComparator(version2, comparator.operator, comparator.operand)) - return false; + if (!testComparator(version2, comparator.operator, comparator.operand)) return false; } return true; } @@ -2579,8 +2526,7 @@ function tryGetPerformance() { } function tryGetPerformanceHooks() { const p = tryGetPerformance(); - if (!p) - return void 0; + if (!p) return void 0; const { shouldWriteNativeEvents, performance: performance2 } = p; const hooks = { shouldWriteNativeEvents, @@ -2677,10 +2623,8 @@ function forEachMark(cb) { marks.forEach((_time, markName) => cb(markName)); } function clearMeasures(name) { - if (name !== void 0) - durations.delete(name); - else - durations.clear(); + if (name !== void 0) durations.delete(name); + else durations.clear(); performanceImpl == null ? void 0 : performanceImpl.clearMeasures(name); } function clearMarks(name) { @@ -2842,15 +2786,12 @@ var tracingEnabled; } } function writeEvent(eventType, phase, name, args, extras, time = 1e3 * timestamp()) { - if (mode === "server" && phase === "checkTypes" /* CheckTypes */) - return; + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; mark("beginTracing"); fs.writeSync(traceFd, `, {"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); - if (extras) - fs.writeSync(traceFd, `,${extras}`); - if (args) - fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); + if (extras) fs.writeSync(traceFd, `,${extras}`); + if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); fs.writeSync(traceFd, `}`); mark("endTracing"); measure("Tracing", "beginTracing", "endTracing"); @@ -3598,6 +3539,34 @@ var SymbolFlags = /* @__PURE__ */ ((SymbolFlags2) => { SymbolFlags2[SymbolFlags2["LateBindingContainer"] = 6256] = "LateBindingContainer"; return SymbolFlags2; })(SymbolFlags || {}); +var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags3) => { + NodeCheckFlags3[NodeCheckFlags3["None"] = 0] = "None"; + NodeCheckFlags3[NodeCheckFlags3["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags3[NodeCheckFlags3["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags3[NodeCheckFlags3["SuperInstance"] = 16] = "SuperInstance"; + NodeCheckFlags3[NodeCheckFlags3["SuperStatic"] = 32] = "SuperStatic"; + NodeCheckFlags3[NodeCheckFlags3["ContextChecked"] = 64] = "ContextChecked"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAccessInAsync"] = 128] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAssignmentInAsync"] = 256] = "MethodWithSuperPropertyAssignmentInAsync"; + NodeCheckFlags3[NodeCheckFlags3["CaptureArguments"] = 512] = "CaptureArguments"; + NodeCheckFlags3[NodeCheckFlags3["EnumValuesComputed"] = 1024] = "EnumValuesComputed"; + NodeCheckFlags3[NodeCheckFlags3["LexicalModuleMergesWithClass"] = 2048] = "LexicalModuleMergesWithClass"; + NodeCheckFlags3[NodeCheckFlags3["LoopWithCapturedBlockScopedBinding"] = 4096] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags3[NodeCheckFlags3["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; + NodeCheckFlags3[NodeCheckFlags3["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags3[NodeCheckFlags3["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags3[NodeCheckFlags3["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags3[NodeCheckFlags3["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags3[NodeCheckFlags3["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; + NodeCheckFlags3[NodeCheckFlags3["LazyFlags"] = 539358128] = "LazyFlags"; + return NodeCheckFlags3; +})(NodeCheckFlags || {}); var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["Any"] = 1] = "Any"; TypeFlags2[TypeFlags2["Unknown"] = 2] = "Unknown"; @@ -3629,6 +3598,7 @@ var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["TemplateLiteral"] = 134217728] = "TemplateLiteral"; TypeFlags2[TypeFlags2["StringMapping"] = 268435456] = "StringMapping"; TypeFlags2[TypeFlags2["Reserved1"] = 536870912] = "Reserved1"; + TypeFlags2[TypeFlags2["Reserved2"] = 1073741824] = "Reserved2"; TypeFlags2[TypeFlags2["AnyOrUnknown"] = 3] = "AnyOrUnknown"; TypeFlags2[TypeFlags2["Nullable"] = 98304] = "Nullable"; TypeFlags2[TypeFlags2["Literal"] = 2944] = "Literal"; @@ -3667,6 +3637,7 @@ var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["IncludesEmptyObject"] = 16777216 /* Conditional */] = "IncludesEmptyObject"; TypeFlags2[TypeFlags2["IncludesInstantiable"] = 33554432 /* Substitution */] = "IncludesInstantiable"; TypeFlags2[TypeFlags2["IncludesConstrainedTypeVariable"] = 536870912 /* Reserved1 */] = "IncludesConstrainedTypeVariable"; + TypeFlags2[TypeFlags2["IncludesError"] = 1073741824 /* Reserved2 */] = "IncludesError"; TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323331] = "NotPrimitiveUnion"; return TypeFlags2; })(TypeFlags || {}); @@ -4171,8 +4142,7 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFi dirName, 1 /* Directory */, (eventName, relativeFileName) => { - if (!isString(relativeFileName)) - return; + if (!isString(relativeFileName)) return; const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); const filePath = toCanonicalName(fileName); const callbacks = fileName && fileWatcherCallbacks.get(filePath); @@ -4183,15 +4153,12 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFi const existingTime = fileTimestamps.get(filePath); if (eventName === "change") { currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime; - if (currentModifiedTime.getTime() === existingTime.getTime()) - return; + if (currentModifiedTime.getTime() === existingTime.getTime()) return; } currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime); fileTimestamps.set(filePath, currentModifiedTime); - if (existingTime === missingFileModifiedTime) - eventKind = 0 /* Created */; - else if (currentModifiedTime === missingFileModifiedTime) - eventKind = 2 /* Deleted */; + if (existingTime === missingFileModifiedTime) eventKind = 0 /* Created */; + else if (currentModifiedTime === missingFileModifiedTime) eventKind = 2 /* Deleted */; } for (const fileCallback of callbacks) { fileCallback(fileName, eventKind, currentModifiedTime); @@ -4234,8 +4201,7 @@ function createFixedChunkSizePollingWatchFile(host) { scheduleNextPoll(); } function scheduleNextPoll() { - if (!watchedFiles.length || pollScheduled) - return; + if (!watchedFiles.length || pollScheduled) return; pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } @@ -4260,10 +4226,8 @@ function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, cal return { close: () => { const watcher = cache.get(path); - if (!watcher) - return; - if (!orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) - return; + if (!watcher) return; + if (!orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) return; cache.delete(path); closeFileWatcherOf(watcher); } @@ -4318,11 +4282,9 @@ function createDirectoryWatcherSupportingRecursive({ dirName, (fileName) => { var _a; - if (isIgnoredPath(fileName, options)) - return; + if (isIgnoredPath(fileName, options)) return; if (options == null ? void 0 : options.synchronousWatchDirectory) { - if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) - invokeCallbacks(dirName, dirPath, fileName); + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, fileName); updateChildWatches(dirName, dirPath, options); } else { nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); @@ -4340,8 +4302,7 @@ function createDirectoryWatcherSupportingRecursive({ cache.set(dirPath, directoryWatcher); updateChildWatches(dirName, dirPath, options); } - if (link) - (directoryWatcher.links ?? (directoryWatcher.links = /* @__PURE__ */ new Set())).add(link); + if (link) (directoryWatcher.links ?? (directoryWatcher.links = /* @__PURE__ */ new Set())).add(link); const callbackToAdd = callback && { dirName, callback }; if (callbackToAdd) { callbackCache.add(dirPath, callbackToAdd); @@ -4351,13 +4312,10 @@ function createDirectoryWatcherSupportingRecursive({ close: () => { var _a; const directoryWatcher2 = Debug.checkDefined(cache.get(dirPath)); - if (callbackToAdd) - callbackCache.remove(dirPath, callbackToAdd); - if (link) - (_a = directoryWatcher2.links) == null ? void 0 : _a.delete(link); + if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd); + if (link) (_a = directoryWatcher2.links) == null ? void 0 : _a.delete(link); directoryWatcher2.refCount--; - if (directoryWatcher2.refCount) - return; + if (directoryWatcher2.refCount) return; cache.delete(dirPath); directoryWatcher2.links = void 0; closeFileWatcherOf(directoryWatcher2); @@ -4376,8 +4334,7 @@ function createDirectoryWatcherSupportingRecursive({ invokeMap = fileNameOrInvokeMap; } callbackCache.forEach((callbacks, rootDirName) => { - if (invokeMap && invokeMap.get(rootDirName) === true) - return; + if (invokeMap && invokeMap.get(rootDirName) === true) return; if (rootDirName === dirPath || startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === directorySeparator) { if (invokeMap) { if (fileNames) { @@ -4439,8 +4396,7 @@ function createDirectoryWatcherSupportingRecursive({ const { value: [dirPath, { dirName, options, fileNames }] } = result; cacheToUpdateChildWatches.delete(dirPath); const hasChanges = updateChildWatches(dirName, dirPath, options); - if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) - invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames); + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames); } sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${timestamp() - start}ms:: ${cacheToUpdateChildWatches.size}`); callbackCache.forEach((callbacks, rootDirName) => { @@ -4459,8 +4415,7 @@ function createDirectoryWatcherSupportingRecursive({ sysLog(`sysLog:: Elapsed:: ${elapsed}ms:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size} ${timerToUpdateChildWatches}`); } function removeChildWatches(parentWatcher) { - if (!parentWatcher) - return; + if (!parentWatcher) return; const existingChildWatches = parentWatcher.childWatches; parentWatcher.childWatches = emptyArray; for (const childWatcher of existingChildWatches) { @@ -4476,8 +4431,7 @@ function createDirectoryWatcherSupportingRecursive({ } function updateChildWatches(parentDir, parentDirPath, options) { const parentWatcher = cache.get(parentDirPath); - if (!parentWatcher) - return false; + if (!parentWatcher) return false; const target = normalizePath(realpath(parentDir)); let hasChanges; let newChildWatches; @@ -4522,10 +4476,8 @@ function createDirectoryWatcherSupportingRecursive({ return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { - if (path.includes(searchPath)) - return true; - if (useCaseSensitiveFileNames2) - return false; + if (path.includes(searchPath)) return true; + if (useCaseSensitiveFileNames2) return false; return toCanonicalFilePath(path).includes(searchPath); } } @@ -4649,8 +4601,7 @@ function createSystemWatchFunctions({ return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); } function updateOptionsForWatchFile(options, useNonPollingWatchers2) { - if (options && options.watchFile !== void 0) - return options; + if (options && options.watchFile !== void 0) return options; switch (tscWatchFile) { case "PriorityPollingInterval": return { watchFile: 1 /* PriorityPollingInterval */ }; @@ -4748,8 +4699,7 @@ function createSystemWatchFunctions({ } } function updateOptionsForWatchDirectory(options) { - if (options && options.watchDirectory !== void 0) - return options; + if (options && options.watchDirectory !== void 0) return options; switch (tscWatchDirectory) { case "RecursiveDirectoryUsingFsWatchFile": return { watchDirectory: 1 /* FixedPollingInterval */ }; @@ -4834,8 +4784,7 @@ function createSystemWatchFunctions({ } if (event === "rename" && (!relativeName || relativeName === lastDirectoryPart || endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { const modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; - if (originalRelativeName) - callback(event, originalRelativeName, modifiedTime); + if (originalRelativeName) callback(event, originalRelativeName, modifiedTime); callback(event, relativeName, modifiedTime); if (inodeWatching) { updateWatcher(modifiedTime === missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); @@ -4843,8 +4792,7 @@ function createSystemWatchFunctions({ updateWatcher(watchMissingFileSystemEntry); } } else { - if (originalRelativeName) - callback(event, originalRelativeName); + if (originalRelativeName) callback(event, originalRelativeName); callback(event, relativeName); } } @@ -4878,8 +4826,7 @@ function createSystemWatchFunctions({ return fsWatchWorker(fileOrDirectory, recursive, (eventName, relativeFileName, currentModifiedTime) => { if (eventName === "change") { currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); - if (currentModifiedTime.getTime() === modifiedTime.getTime()) - return; + if (currentModifiedTime.getTime() === modifiedTime.getTime()) return; } modifiedTime = currentModifiedTime || getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; callback(eventName, relativeFileName, modifiedTime); @@ -5395,33 +5342,26 @@ function isVolumeCharacter(charCode) { } function getFileUrlVolumeSeparatorEnd(url, start) { const ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; + if (ch0 === 58 /* colon */) return start + 1; if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { const ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) return start + 3; } return -1; } function getEncodedRootLength(path) { - if (!path) - return 0; + if (!path) return 0; const ch0 = path.charCodeAt(0); if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; + if (path.charCodeAt(1) !== ch0) return 1; const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; + if (p1 < 0) return path.length; return p1 + 1; } if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { const ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; - if (path.length === 2) - return 2; + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) return 3; + if (path.length === 2) return 2; } const schemeEnd = path.indexOf(urlSchemeSeparator); if (schemeEnd !== -1) { @@ -5454,24 +5394,21 @@ function getRootLength(path) { function getDirectoryPath(path) { path = normalizeSlashes(path); const rootLength = getRootLength(path); - if (rootLength === path.length) - return path; + if (rootLength === path.length) return path; path = removeTrailingDirectorySeparator(path); return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); } function getBaseFileName(path, extensions, ignoreCase) { path = normalizeSlashes(path); const rootLength = getRootLength(path); - if (rootLength === path.length) - return ""; + if (rootLength === path.length) return ""; path = removeTrailingDirectorySeparator(path); const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1)); const extension = extensions !== void 0 && ignoreCase !== void 0 ? getAnyExtensionFromPath(name, extensions, ignoreCase) : void 0; return extension ? name.slice(0, name.length - extension.length) : name; } function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { - if (!startsWith(extension, ".")) - extension = "." + extension; + if (!startsWith(extension, ".")) extension = "." + extension; if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { const pathExtension = path.slice(path.length - extension.length); if (stringEqualityComparer(pathExtension, extension)) { @@ -5485,8 +5422,7 @@ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) } for (const extension of extensions) { const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); - if (result) - return result; + if (result) return result; } return ""; } @@ -5504,8 +5440,7 @@ function getAnyExtensionFromPath(path, extensions, ignoreCase) { function pathComponents(path, rootLength) { const root = path.substring(0, rootLength); const rest = path.substring(rootLength).split(directorySeparator); - if (rest.length && !lastOrUndefined(rest)) - rest.pop(); + if (rest.length && !lastOrUndefined(rest)) rest.pop(); return [root, ...rest]; } function getPathComponents(path, currentDirectory = "") { @@ -5513,8 +5448,7 @@ function getPathComponents(path, currentDirectory = "") { return pathComponents(path, getRootLength(path)); } function getPathFromPathComponents(pathComponents2, length2) { - if (pathComponents2.length === 0) - return ""; + if (pathComponents2.length === 0) return ""; const root = pathComponents2[0] && ensureTrailingDirectorySeparator(pathComponents2[0]); return root + pathComponents2.slice(1, length2).join(directorySeparator); } @@ -5522,34 +5456,28 @@ function normalizeSlashes(path) { return path.includes("\\") ? path.replace(backslashRegExp, directorySeparator) : path; } function reducePathComponents(components) { - if (!some(components)) - return []; + if (!some(components)) return []; const reduced = [components[0]]; for (let i = 1; i < components.length; i++) { const component = components[i]; - if (!component) - continue; - if (component === ".") - continue; + 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; + } else if (reduced[0]) continue; } reduced.push(component); } return reduced; } function combinePaths(path, ...paths) { - if (path) - path = normalizeSlashes(path); + if (path) path = normalizeSlashes(path); for (let relativePath of paths) { - if (!relativePath) - continue; + if (!relativePath) continue; relativePath = normalizeSlashes(relativePath); if (!path || getRootLength(relativePath) !== 0) { path = relativePath; @@ -5584,8 +5512,7 @@ function normalizePath(path) { return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; } function getPathWithoutRoot(pathComponents2) { - if (pathComponents2.length === 0) - return ""; + if (pathComponents2.length === 0) return ""; return pathComponents2.slice(1).join(directorySeparator); } function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { @@ -5616,12 +5543,9 @@ function changeAnyExtension(path, ext, extensions, ignoreCase) { } var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; const aRoot = a.substring(0, getRootLength(a)); const bRoot = b.substring(0, getRootLength(b)); const result = compareStringsCaseInsensitive(aRoot, bRoot); @@ -5660,10 +5584,8 @@ function containsPath(parent, child, currentDirectory, ignoreCase) { } else if (typeof currentDirectory === "boolean") { ignoreCase = currentDirectory; } - if (parent === void 0 || child === void 0) - return false; - if (parent === child) - return true; + if (parent === void 0 || child === void 0) return false; + if (parent === child) return true; const parentComponents = reducePathComponents(getPathComponents(parent)); const childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { @@ -5691,8 +5613,7 @@ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanoni const fromComponent = getCanonicalFileName(fromComponents[start]); const toComponent = getCanonicalFileName(toComponents[start]); const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; + if (!comparer(fromComponent, toComponent)) break; } if (start === 0) { return toComponents; @@ -6193,7 +6114,7 @@ var Diagnostics = { Range_out_of_order_in_character_class: diag(1517, 1 /* Error */, "Range_out_of_order_in_character_class_1517", "Range out of order in character class."), Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class: diag(1518, 1 /* Error */, "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518", "Anything that would possibly match more than a single character is invalid inside a negated character class."), Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead: diag(1519, 1 /* Error */, "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519", "Operators must not be mixed within a character class. Wrap it in a nested class instead."), - Expected_a_class_set_oprand: diag(1520, 1 /* Error */, "Expected_a_class_set_oprand_1520", "Expected a class set oprand."), + Expected_a_class_set_operand: diag(1520, 1 /* Error */, "Expected_a_class_set_operand_1520", "Expected a class set operand."), q_must_be_followed_by_string_alternatives_enclosed_in_braces: diag(1521, 1 /* Error */, "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521", "'\\q' must be followed by string alternatives enclosed in braces."), A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash: diag(1522, 1 /* Error */, "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522", "A character class must not contain a reserved double punctuator. Did you mean to escape it with backslash?"), Expected_a_Unicode_property_name: diag(1523, 1 /* Error */, "Expected_a_Unicode_property_name_1523", "Expected a Unicode property name."), @@ -6207,8 +6128,10 @@ var Diagnostics = { _0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces: diag(1531, 1 /* Error */, "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531", "'\\{0}' must be followed by a Unicode property value expression enclosed in braces."), There_is_no_capturing_group_named_0_in_this_regular_expression: diag(1532, 1 /* Error */, "There_is_no_capturing_group_named_0_in_this_regular_expression_1532", "There is no capturing group named '{0}' in this regular expression."), This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression: diag(1533, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533", "This backreference refers to a group that does not exist. There are only {0} capturing groups in this regular expression."), - This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups: diag(1534, 1 /* Error */, "This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups_1534", "This backreference is invalid because the containing regular expression contains no capturing groups."), + This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression: diag(1534, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534", "This backreference refers to a group that does not exist. There are no capturing groups in this regular expression."), This_character_cannot_be_escaped_in_a_regular_expression: diag(1535, 1 /* Error */, "This_character_cannot_be_escaped_in_a_regular_expression_1535", "This character cannot be escaped in a regular expression."), + Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead: diag(1536, 1 /* Error */, "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536", "Octal escape sequences and backreferences are not allowed in a character class. If this was intended as an escape sequence, use the syntax '{0}' instead."), + Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class: diag(1537, 1 /* Error */, "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537", "Decimal escape sequences and backreferences are not allowed in a character class."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag( @@ -6850,7 +6773,6 @@ var Diagnostics = { Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, 1 /* Error */, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, 1 /* Error */, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1: diag(4085, 1 /* Error */, "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085", "Extends clause for inferred type '{0}' has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, 1 /* Error */, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, 1 /* Error */, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), @@ -7457,6 +7379,7 @@ var Diagnostics = { Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files: diag(6719, 3 /* Message */, "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719", "Require sufficient annotation on exports so other tools can trivially generate declaration files."), Default_catch_clause_variables_as_unknown_instead_of_any: diag(6803, 3 /* Message */, "Default_catch_clause_variables_as_unknown_instead_of_any_6803", "Default catch clause variables as 'unknown' instead of 'any'."), Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting: diag(6804, 3 /* Message */, "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804", "Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting."), + Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported: diag(6805, 3 /* Message */, "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805", "Disable full type checking (only critical parse and emit errors will be reported)."), one_of_Colon: diag(6900, 3 /* Message */, "one_of_Colon_6900", "one of:"), one_or_more_Colon: diag(6901, 3 /* Message */, "one_or_more_Colon_6901", "one or more:"), type_Colon: diag(6902, 3 /* Message */, "type_Colon_6902", "type:"), @@ -7626,6 +7549,8 @@ var Diagnostics = { Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit: diag(9035, 1 /* Error */, "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035", "Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit."), Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it: diag(9036, 1 /* Error */, "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036", "Move the expression in default export to a variable and add a type annotation to it."), Default_exports_can_t_be_inferred_with_isolatedDeclarations: diag(9037, 1 /* Error */, "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037", "Default exports can't be inferred with --isolatedDeclarations."), + Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations: diag(9038, 1 /* Error */, "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038", "Computed property names on class or object literals cannot be inferred with --isolatedDeclarations."), + Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations: diag(9039, 1 /* Error */, "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039", "Type containing private name '{0}' can't be used with --isolatedDeclarations."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, 1 /* Error */, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), Expected_corresponding_JSX_closing_tag_for_0: diag(17002, 1 /* Error */, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), @@ -7705,6 +7630,16 @@ var Diagnostics = { Export_0_from_module_1: diag(90059, 3 /* Message */, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), Export_all_referenced_locals: diag(90060, 3 /* Message */, "Export_all_referenced_locals_90060", "Export all referenced locals"), Update_modifiers_of_0: diag(90061, 3 /* Message */, "Update_modifiers_of_0_90061", "Update modifiers of '{0}'"), + Add_annotation_of_type_0: diag(90062, 3 /* Message */, "Add_annotation_of_type_0_90062", "Add annotation of type '{0}'"), + Add_return_type_0: diag(90063, 3 /* Message */, "Add_return_type_0_90063", "Add return type '{0}'"), + Extract_base_class_to_variable: diag(90064, 3 /* Message */, "Extract_base_class_to_variable_90064", "Extract base class to variable"), + Extract_default_export_to_variable: diag(90065, 3 /* Message */, "Extract_default_export_to_variable_90065", "Extract default export to variable"), + Extract_binding_expressions_to_variable: diag(90066, 3 /* Message */, "Extract_binding_expressions_to_variable_90066", "Extract binding expressions to variable"), + Add_all_missing_type_annotations: diag(90067, 3 /* Message */, "Add_all_missing_type_annotations_90067", "Add all missing type annotations"), + Add_satisfies_and_an_inline_type_assertion_with_0: diag(90068, 3 /* Message */, "Add_satisfies_and_an_inline_type_assertion_with_0_90068", "Add satisfies and an inline type assertion with '{0}'"), + Extract_to_variable_and_replace_with_0_as_typeof_0: diag(90069, 3 /* Message */, "Extract_to_variable_and_replace_with_0_as_typeof_0_90069", "Extract to variable and replace with '{0} as typeof {0}'"), + Mark_array_literal_as_const: diag(90070, 3 /* Message */, "Mark_array_literal_as_const_90070", "Mark array literal as const"), + Annotate_types_of_properties_expando_function_in_a_namespace: diag(90071, 3 /* Message */, "Annotate_types_of_properties_expando_function_in_a_namespace_90071", "Annotate types of properties expando function in a namespace"), Convert_function_to_an_ES2015_class: diag(95001, 3 /* Message */, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_0_to_1_in_0: diag(95003, 3 /* Message */, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, 3 /* Message */, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -8109,19 +8044,16 @@ var charToRegExpFlag = new Map(Object.entries({ y: 128 /* Sticky */ })); var regExpFlagToFirstAvailableLanguageVersion = /* @__PURE__ */ new Map([ - [1 /* HasIndices */, 9 /* ES2022 */], - [2 /* Global */, 0 /* ES3 */], - [4 /* IgnoreCase */, 0 /* ES3 */], - [8 /* Multiline */, 0 /* ES3 */], - [16 /* DotAll */, 5 /* ES2018 */], - [32 /* Unicode */, 2 /* ES2015 */], - [64 /* UnicodeSets */, 99 /* ESNext */], - [128 /* Sticky */, 2 /* ES2015 */] + [1 /* HasIndices */, 9 /* RegularExpressionFlagsHasIndices */], + [16 /* DotAll */, 5 /* RegularExpressionFlagsDotAll */], + [32 /* Unicode */, 2 /* RegularExpressionFlagsUnicode */], + [64 /* UnicodeSets */, 99 /* RegularExpressionFlagsUnicodeSets */], + [128 /* Sticky */, 2 /* RegularExpressionFlagsSticky */] ]); var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; -var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; -var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; +var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2160, 2183, 2185, 2190, 2208, 2249, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3165, 3165, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3293, 3294, 3296, 3297, 3313, 3314, 3332, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5905, 5919, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6988, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69248, 69289, 69296, 69297, 69376, 69404, 69415, 69415, 69424, 69445, 69488, 69505, 69552, 69572, 69600, 69622, 69635, 69687, 69745, 69746, 69749, 69749, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69959, 69959, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70207, 70208, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70753, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71488, 71494, 71680, 71723, 71840, 71903, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71983, 71999, 71999, 72001, 72001, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73474, 73474, 73476, 73488, 73490, 73523, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78913, 78918, 82944, 83526, 92160, 92728, 92736, 92766, 92784, 92862, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 122624, 122654, 122661, 122666, 122928, 122989, 123136, 123180, 123191, 123197, 123214, 123214, 123536, 123565, 123584, 123627, 124112, 124139, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743]; +var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2160, 2183, 2185, 2190, 2200, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2901, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3132, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3165, 3165, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3293, 3294, 3296, 3299, 3302, 3311, 3313, 3315, 3328, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3457, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3790, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5909, 5919, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6159, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6847, 6862, 6912, 6988, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43047, 43052, 43052, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69248, 69289, 69291, 69292, 69296, 69297, 69373, 69404, 69415, 69415, 69424, 69456, 69488, 69509, 69552, 69572, 69600, 69622, 69632, 69702, 69734, 69749, 69759, 69818, 69826, 69826, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69959, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70094, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70209, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70753, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71488, 71494, 71680, 71738, 71840, 71913, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71989, 71991, 71992, 71995, 72003, 72016, 72025, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73472, 73488, 73490, 73530, 73534, 73538, 73552, 73561, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78912, 78933, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92784, 92862, 92864, 92873, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94180, 94192, 94193, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 118528, 118573, 118576, 118598, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122624, 122654, 122661, 122666, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 122928, 122989, 123023, 123023, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123536, 123566, 123584, 123641, 124112, 124153, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 130032, 130041, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743, 917760, 917999]; var commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/; var commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; var jsDocSeeOrLink = /@(?:see|link)/i; @@ -8238,8 +8170,7 @@ function computeLineOfPosition(lineStarts, position, lowerBound) { return lineNumber; } function getLinesBetweenPositions(sourceFile, pos1, pos2) { - if (pos1 === pos2) - return 0; + if (pos1 === pos2) return 0; const lineStarts = getLineStarts(sourceFile); const lower = Math.min(pos1, pos2); const isNegative = lower === pos2; @@ -8681,6 +8612,18 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan }); } return scanner; + function codePointUnchecked(pos2) { + return codePointAt(text, pos2); + } + function codePointChecked(pos2) { + return pos2 >= 0 && pos2 < end ? codePointUnchecked(pos2) : -1 /* EOF */; + } + function charCodeUnchecked(pos2) { + return text.charCodeAt(pos2); + } + function charCodeChecked(pos2) { + return pos2 >= 0 && pos2 < end ? charCodeUnchecked(pos2) : -1 /* EOF */; + } function error(message, errPos = pos, length3, arg0) { if (onError) { const oldPos = pos; @@ -8695,7 +8638,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let isPreviousTokenSeparator = false; let result = ""; while (true) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (allowSeparator) { @@ -8722,7 +8665,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } break; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { tokenFlags |= 16384 /* ContainsInvalidSeparator */; error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } @@ -8731,9 +8674,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanNumber() { let start2 = pos; let mainFragment; - if (text.charCodeAt(pos) === 48 /* _0 */) { + if (charCodeUnchecked(pos) === 48 /* _0 */) { pos++; - if (text.charCodeAt(pos) === 95 /* _ */) { + if (charCodeUnchecked(pos) === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */ | 16384 /* ContainsInvalidSeparator */; error(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); pos--; @@ -8748,8 +8691,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 32 /* Octal */; const withMinus = token === 41 /* MinusToken */; const literal = (withMinus ? "-" : "") + "0o" + (+tokenValue).toString(8); - if (withMinus) - start2--; + if (withMinus) start2--; error(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); return 9 /* NumericLiteral */; } @@ -8758,16 +8700,15 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } let decimalFragment; let scientificFragment; - if (text.charCodeAt(pos) === 46 /* dot */) { + if (charCodeUnchecked(pos) === 46 /* dot */) { pos++; decimalFragment = scanNumberFragment(); } let end2 = pos; - if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + if (charCodeUnchecked(pos) === 69 /* E */ || charCodeUnchecked(pos) === 101 /* e */) { pos++; tokenFlags |= 16 /* Scientific */; - if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) - pos++; + if (charCodeUnchecked(pos) === 43 /* plus */ || charCodeUnchecked(pos) === 45 /* minus */) pos++; const preNumericPart = pos; const finalFragment = scanNumberFragment(); if (!finalFragment) { @@ -8806,7 +8747,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { - if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) { + if (!isIdentifierStart(codePointUnchecked(pos), languageVersion)) { return; } const identifierStart = pos; @@ -8825,8 +8766,8 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanDigits() { const start2 = pos; let isOctal = true; - while (isDigit(text.charCodeAt(pos))) { - if (!isOctalDigit(text.charCodeAt(pos))) { + while (isDigit(charCodeChecked(pos))) { + if (!isOctalDigit(charCodeUnchecked(pos))) { isOctal = false; } pos++; @@ -8858,7 +8799,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let allowSeparator = false; let isPreviousTokenSeparator = false; while (valueChars.length < minCount || scanAsManyAsPossible) { - let ch = text.charCodeAt(pos); + let ch = charCodeUnchecked(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (allowSeparator) { @@ -8885,13 +8826,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (valueChars.length < minCount) { valueChars = []; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } return String.fromCharCode(...valueChars); } function scanString(jsxAttributeString = false) { - const quote = text.charCodeAt(pos); + const quote = charCodeUnchecked(pos); pos++; let result = ""; let start2 = pos; @@ -8902,7 +8843,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan error(Diagnostics.Unterminated_string_literal); break; } - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === quote) { result += text.substring(start2, pos); pos++; @@ -8910,12 +8851,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start2, pos); - result += scanEscapeSequence( - /*shouldEmitInvalidEscapeError*/ - true, - /*isRegularExpression*/ - false - ); + result += scanEscapeSequence(1 /* String */ | 2 /* ReportErrors */); start2 = pos; continue; } @@ -8930,7 +8866,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return result; } function scanTemplateAndSetTokenValue(shouldEmitInvalidEscapeError) { - const startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + const startedWithBacktick = charCodeUnchecked(pos) === 96 /* backtick */; pos++; let start2 = pos; let contents = ""; @@ -8943,14 +8879,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; break; } - const currChar = text.charCodeAt(pos); + const currChar = charCodeUnchecked(pos); if (currChar === 96 /* backtick */) { contents += text.substring(start2, pos); pos++; resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; break; } - if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + if (currChar === 36 /* $ */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 123 /* openBrace */) { contents += text.substring(start2, pos); pos += 2; resultingToken = startedWithBacktick ? 16 /* TemplateHead */ : 17 /* TemplateMiddle */; @@ -8958,18 +8894,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (currChar === 92 /* backslash */) { contents += text.substring(start2, pos); - contents += scanEscapeSequence( - shouldEmitInvalidEscapeError, - /*isRegularExpression*/ - false - ); + contents += scanEscapeSequence(1 /* String */ | (shouldEmitInvalidEscapeError ? 2 /* ReportErrors */ : 0)); start2 = pos; continue; } if (currChar === 13 /* carriageReturn */) { contents += text.substring(start2, pos); pos++; - if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } contents += "\n"; @@ -8982,37 +8914,39 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = contents; return resultingToken; } - function scanEscapeSequence(shouldEmitInvalidEscapeError, isRegularExpression) { + function scanEscapeSequence(flags) { const start2 = pos; pos++; if (pos >= end) { error(Diagnostics.Unexpected_end_of_text); return ""; } - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); pos++; switch (ch) { case 48 /* _0 */: - if (pos >= end || !isDigit(text.charCodeAt(pos))) { + if (pos >= end || !isDigit(charCodeUnchecked(pos))) { return "\0"; } case 49 /* _1 */: case 50 /* _2 */: case 51 /* _3 */: - if (pos < end && isOctalDigit(text.charCodeAt(pos))) { + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { pos++; } case 52 /* _4 */: case 53 /* _5 */: case 54 /* _6 */: case 55 /* _7 */: - if (pos < end && isOctalDigit(text.charCodeAt(pos))) { + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { pos++; } tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { const code = parseInt(text.substring(start2 + 1, pos), 8); - if (isRegularExpression !== "annex-b") { + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */) && ch !== 48 /* _0 */) { + error(Diagnostics.Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); + } else { error(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); } return String.fromCharCode(code); @@ -9021,8 +8955,12 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 56 /* _8 */: case 57 /* _9 */: tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { - error(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + if (flags & 6 /* ReportInvalidEscapeErrors */) { + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */)) { + error(Diagnostics.Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class, start2, pos - start2); + } else { + error(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + } return String.fromCharCode(ch); } return text.substring(start2, pos); @@ -9043,14 +8981,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 34 /* doubleQuote */: return '"'; case 117 /* u */: - if ((!isRegularExpression || shouldEmitInvalidEscapeError) && pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + if (flags & 17 /* ScanExtendedUnicodeEscape */ && pos < end && charCodeUnchecked(pos) === 123 /* openBrace */) { pos -= 2; - return scanExtendedUnicodeEscape(!!isRegularExpression || shouldEmitInvalidEscapeError); + return scanExtendedUnicodeEscape(!!(flags & 6 /* ReportInvalidEscapeErrors */)); } for (; pos < start2 + 6; pos++) { - if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { error(Diagnostics.Hexadecimal_digit_expected); } return text.substring(start2, pos); @@ -9059,11 +8997,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 1024 /* UnicodeEscape */; const escapedValue = parseInt(text.substring(start2 + 2, pos), 16); const escapedValueString = String.fromCharCode(escapedValue); - if (isRegularExpression && shouldEmitInvalidEscapeError && escapedValue >= 55296 && escapedValue <= 56319 && pos + 6 < end && text.substring(pos, pos + 2) === "\\u" && text.charCodeAt(pos + 2) !== 123 /* openBrace */) { + if (flags & 16 /* AnyUnicodeMode */ && escapedValue >= 55296 && escapedValue <= 56319 && pos + 6 < end && text.substring(pos, pos + 2) === "\\u" && charCodeUnchecked(pos + 2) !== 123 /* openBrace */) { const nextStart = pos; let nextPos = pos + 2; for (; nextPos < nextStart + 6; nextPos++) { - if (!isHexDigit(text.charCodeAt(pos))) { + if (!isHexDigit(charCodeUnchecked(pos))) { return escapedValueString; } } @@ -9076,9 +9014,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return escapedValueString; case 120 /* x */: for (; pos < start2 + 4; pos++) { - if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { error(Diagnostics.Hexadecimal_digit_expected); } return text.substring(start2, pos); @@ -9087,7 +9025,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 4096 /* HexEscape */; return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); case 13 /* carriageReturn */: - if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } case 10 /* lineFeed */: @@ -9095,7 +9033,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 8233 /* paragraphSeparator */: return ""; default: - if (isRegularExpression === true && (shouldEmitInvalidEscapeError || isIdentifierPart(ch, languageVersion))) { + if (flags & 16 /* AnyUnicodeMode */ || flags & 4 /* RegularExpression */ && !(flags & 8 /* AnnexB */) && isIdentifierPart(ch, languageVersion)) { error(Diagnostics.This_character_cannot_be_escaped_in_a_regular_expression, pos - 2, 2); } return String.fromCharCode(ch); @@ -9128,7 +9066,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan error(Diagnostics.Unexpected_end_of_text); } isInvalidExtendedEscape = true; - } else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + } else if (charCodeUnchecked(pos) === 125 /* closeBrace */) { pos++; } else { if (shouldEmitInvalidEscapeError) { @@ -9144,7 +9082,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return utf16EncodeAsString(escapedValue); } function peekUnicodeEscape() { - if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + if (pos + 5 < end && charCodeUnchecked(pos + 1) === 117 /* u */) { const start2 = pos; pos += 2; const value = scanExactNumberOfHexDigits( @@ -9158,7 +9096,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return -1; } function peekExtendedUnicodeEscape() { - if (codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) { + if (codePointUnchecked(pos + 1) === 117 /* u */ && codePointUnchecked(pos + 2) === 123 /* openBrace */) { const start2 = pos; pos += 3; const escapedValueString = scanMinimumNumberOfHexDigits( @@ -9176,7 +9114,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let result = ""; let start2 = pos; while (pos < end) { - let ch = codePointAt(text, pos); + let ch = codePointUnchecked(pos); if (isIdentifierPart(ch, languageVersion)) { pos += charSize(ch); } else if (ch === 92 /* backslash */) { @@ -9223,7 +9161,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let separatorAllowed = false; let isPreviousTokenSeparator = false; while (true) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -9245,13 +9183,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; isPreviousTokenSeparator = false; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { error(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } return value; } function checkBigIntSuffix() { - if (text.charCodeAt(pos) === 110 /* n */) { + if (charCodeUnchecked(pos) === 110 /* n */) { tokenValue += "n"; if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { tokenValue = parsePseudoBigInt(tokenValue) + "n"; @@ -9273,7 +9211,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); if (pos === 0) { if (ch === 35 /* hash */ && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); @@ -9292,7 +9230,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; continue; } else { - if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 10 /* lineFeed */) { pos += 2; } else { pos++; @@ -9325,14 +9263,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; continue; } else { - while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { pos++; } return token = 5 /* WhitespaceTrivia */; } case 33 /* exclamation */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 38 /* ExclamationEqualsEqualsToken */; } return pos += 2, token = 36 /* ExclamationEqualsToken */; @@ -9349,19 +9287,19 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan false ); case 37 /* percent */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 70 /* PercentEqualsToken */; } pos++; return token = 45 /* PercentToken */; case 38 /* ampersand */: - if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 38 /* ampersand */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 77 /* AmpersandAmpersandEqualsToken */; } return pos += 2, token = 56 /* AmpersandAmpersandToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 74 /* AmpersandEqualsToken */; } pos++; @@ -9373,11 +9311,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 22 /* CloseParenToken */; case 42 /* asterisk */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* AsteriskEqualsToken */; } - if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 68 /* AsteriskAsteriskEqualsToken */; } return pos += 2, token = 43 /* AsteriskAsteriskToken */; @@ -9389,10 +9327,10 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } return token = 42 /* AsteriskToken */; case 43 /* plus */: - if (text.charCodeAt(pos + 1) === 43 /* plus */) { + if (charCodeUnchecked(pos + 1) === 43 /* plus */) { return pos += 2, token = 46 /* PlusPlusToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 65 /* PlusEqualsToken */; } pos++; @@ -9401,29 +9339,29 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 28 /* CommaToken */; case 45 /* minus */: - if (text.charCodeAt(pos + 1) === 45 /* minus */) { + if (charCodeUnchecked(pos + 1) === 45 /* minus */) { return pos += 2, token = 47 /* MinusMinusToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* MinusEqualsToken */; } pos++; return token = 41 /* MinusToken */; case 46 /* dot */: - if (isDigit(text.charCodeAt(pos + 1))) { + if (isDigit(charCodeUnchecked(pos + 1))) { scanNumber(); return token = 9 /* NumericLiteral */; } - if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && charCodeUnchecked(pos + 2) === 46 /* dot */) { return pos += 3, token = 26 /* DotDotDotToken */; } pos++; return token = 25 /* DotToken */; case 47 /* slash */: - if (text.charCodeAt(pos + 1) === 47 /* slash */) { + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; while (pos < end) { - if (isLineBreak(text.charCodeAt(pos))) { + if (isLineBreak(charCodeUnchecked(pos))) { break; } pos++; @@ -9440,14 +9378,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 2 /* SingleLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { pos += 2; - const isJSDoc2 = text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */; + const isJSDoc2 = charCodeUnchecked(pos) === 42 /* asterisk */ && charCodeUnchecked(pos + 1) !== 47 /* slash */; let commentClosed = false; let lastLineStart = tokenStart; while (pos < end) { - const ch2 = text.charCodeAt(pos); - if (ch2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + const ch2 = charCodeUnchecked(pos); + if (ch2 === 42 /* asterisk */ && charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; commentClosed = true; break; @@ -9474,13 +9412,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 3 /* MultiLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 69 /* SlashEqualsToken */; } pos++; return token = 44 /* SlashToken */; case 48 /* _0 */: - if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 88 /* X */ || charCodeUnchecked(pos + 1) === 120 /* x */)) { pos += 2; tokenValue = scanMinimumNumberOfHexDigits( 1, @@ -9494,7 +9432,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; return token = checkBigIntSuffix(); - } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 66 /* B */ || charCodeUnchecked(pos + 1) === 98 /* b */)) { pos += 2; tokenValue = scanBinaryOrOctalDigits( /* base */ @@ -9507,7 +9445,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; return token = checkBigIntSuffix(); - } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 79 /* O */ || charCodeUnchecked(pos + 1) === 111 /* o */)) { pos += 2; tokenValue = scanBinaryOrOctalDigits( /* base */ @@ -9546,16 +9484,16 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 60 /* lessThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 71 /* LessThanLessThanEqualsToken */; } return pos += 2, token = 48 /* LessThanLessThanToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 33 /* LessThanEqualsToken */; } - if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + if (languageVariant === 1 /* JSX */ && charCodeUnchecked(pos + 1) === 47 /* slash */ && charCodeUnchecked(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 31 /* LessThanSlashToken */; } pos++; @@ -9569,13 +9507,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 37 /* EqualsEqualsEqualsToken */; } return pos += 2, token = 35 /* EqualsEqualsToken */; } - if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 39 /* EqualsGreaterThanToken */; } pos++; @@ -9592,11 +9530,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 32 /* GreaterThanToken */; case 63 /* question */: - if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) { + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && !isDigit(charCodeUnchecked(pos + 2))) { return pos += 2, token = 29 /* QuestionDotToken */; } - if (text.charCodeAt(pos + 1) === 63 /* question */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 63 /* question */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 78 /* QuestionQuestionEqualsToken */; } return pos += 2, token = 61 /* QuestionQuestionToken */; @@ -9610,7 +9548,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 24 /* CloseBracketToken */; case 94 /* caret */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 79 /* CaretEqualsToken */; } pos++; @@ -9627,13 +9565,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 124 /* bar */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 124 /* bar */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 76 /* BarBarEqualsToken */; } return pos += 2, token = 57 /* BarBarToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 75 /* BarEqualsToken */; } pos++; @@ -9672,7 +9610,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 0 /* Unknown */; } - const charAfterHash = codePointAt(text, pos + 1); + const charAfterHash = codePointUnchecked(pos + 1); if (charAfterHash === 92 /* backslash */) { pos++; const extendedCookedChar2 = peekExtendedUnicodeEscape(); @@ -9742,7 +9680,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); pos = tokenStart = fullStartPos; tokenFlags = 0; - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); const identifierKind = scanIdentifier(ch, 99 /* ESNext */); if (identifierKind) { return token = identifierKind; @@ -9754,8 +9692,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let ch = startCharacter; if (isIdentifierStart(ch, languageVersion2)) { pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion2)) - pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointUnchecked(pos), languageVersion2)) pos += charSize(ch); tokenValue = text.substring(tokenStart, pos); if (ch === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -9765,20 +9702,20 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function reScanGreaterToken() { if (token === 32 /* GreaterThanToken */) { - if (text.charCodeAt(pos) === 62 /* greaterThan */) { - if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } return pos += 2, token = 50 /* GreaterThanGreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 72 /* GreaterThanGreaterThanEqualsToken */; } pos++; return token = 49 /* GreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos) === 61 /* equals */) { + if (charCodeUnchecked(pos) === 61 /* equals */) { pos++; return token = 34 /* GreaterThanEqualsToken */; } @@ -9792,25 +9729,20 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function reScanSlashToken(reportErrors2) { if (token === 44 /* SlashToken */ || token === 69 /* SlashEqualsToken */) { - let p = tokenStart + 1; + const startOfRegExpBody = tokenStart + 1; + pos = startOfRegExpBody; let inEscape = false; + let namedCaptureGroups = false; let inCharacterClass = false; while (true) { - if (p >= end) { - tokenFlags |= 4 /* Unterminated */; - error(Diagnostics.Unterminated_regular_expression_literal); - break; - } - const ch = text.charCodeAt(p); - if (isLineBreak(ch)) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || isLineBreak(ch)) { tokenFlags |= 4 /* Unterminated */; - error(Diagnostics.Unterminated_regular_expression_literal); break; } if (inEscape) { inEscape = false; } else if (ch === 47 /* slash */ && !inCharacterClass) { - p++; break; } else if (ch === 91 /* openBracket */) { inCharacterClass = true; @@ -9818,871 +9750,918 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan inEscape = true; } else if (ch === 93 /* closeBracket */) { inCharacterClass = false; + } else if (!inCharacterClass && ch === 40 /* openParen */ && charCodeChecked(pos + 1) === 63 /* question */ && charCodeChecked(pos + 2) === 60 /* lessThan */ && charCodeChecked(pos + 3) !== 61 /* equals */ && charCodeChecked(pos + 3) !== 33 /* exclamation */) { + namedCaptureGroups = true; } - p++; + pos++; } - const isUnterminated = !!(tokenFlags & 4 /* Unterminated */); - const endOfBody = p - (isUnterminated ? 0 : 1); - let regExpFlags = 0 /* None */; - while (p < end) { - const ch = text.charCodeAt(p); - if (!isIdentifierPart(ch, languageVersion)) { - break; + const endOfRegExpBody = pos; + if (tokenFlags & 4 /* Unterminated */) { + pos = startOfRegExpBody; + inEscape = false; + let characterClassDepth = 0; + let inDecimalQuantifier = false; + let groupDepth = 0; + while (pos < endOfRegExpBody) { + const ch = charCodeUnchecked(pos); + if (inEscape) { + inEscape = false; + } else if (ch === 92 /* backslash */) { + inEscape = true; + } else if (ch === 91 /* openBracket */) { + characterClassDepth++; + } else if (ch === 93 /* closeBracket */ && characterClassDepth) { + characterClassDepth--; + } else if (!characterClassDepth) { + if (ch === 123 /* openBrace */) { + inDecimalQuantifier = true; + } else if (ch === 125 /* closeBrace */ && inDecimalQuantifier) { + inDecimalQuantifier = false; + } else if (!inDecimalQuantifier) { + if (ch === 40 /* openParen */) { + groupDepth++; + } else if (ch === 41 /* closeParen */ && groupDepth) { + groupDepth--; + } else if (ch === 41 /* closeParen */ || ch === 93 /* closeBracket */ || ch === 125 /* closeBrace */) { + break; + } + } + } + pos++; } - if (reportErrors2) { - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); - if (flag === void 0) { - error(Diagnostics.Unknown_regular_expression_flag, p, 1); - } else if (regExpFlags & flag) { - error(Diagnostics.Duplicate_regular_expression_flag, p, 1); - } else if (((regExpFlags | flag) & 96 /* UnicodeMode */) === 96 /* UnicodeMode */) { - error(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, p, 1); - } else { - regExpFlags |= flag; - const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); - if (languageVersion < availableFrom) { - error(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, p, 1, getNameOfScriptTarget(availableFrom)); + while (isWhiteSpaceLike(charCodeChecked(pos - 1)) || charCodeChecked(pos - 1) === 59 /* semicolon */) pos--; + error(Diagnostics.Unterminated_regular_expression_literal, tokenStart, pos - tokenStart); + } else { + pos++; + let regExpFlags = 0 /* None */; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + if (reportErrors2) { + const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + if (flag === void 0) { + error(Diagnostics.Unknown_regular_expression_flag, pos, 1); + } else if (regExpFlags & flag) { + error(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + } else if (((regExpFlags | flag) & 96 /* AnyUnicodeMode */) === 96 /* AnyUnicodeMode */) { + error(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, pos, 1); + } else { + regExpFlags |= flag; + checkRegularExpressionFlagAvailable(flag, pos); } } + pos++; } - p++; - } - if (reportErrors2) { - pos = tokenStart + 1; - const saveTokenPos = tokenStart; - const saveTokenFlags = tokenFlags; - scanRegularExpressionWorker( - text, - endOfBody, - regExpFlags, - isUnterminated, - /*annexB*/ - true - ); - if (!isUnterminated) { - pos = p; + if (reportErrors2) { + scanRange(startOfRegExpBody, endOfRegExpBody - startOfRegExpBody, () => { + scanRegularExpressionWorker( + regExpFlags, + /*annexB*/ + true, + namedCaptureGroups + ); + }); } - tokenStart = saveTokenPos; - tokenFlags = saveTokenFlags; - } else { - pos = p; } tokenValue = text.substring(tokenStart, pos); token = 14 /* RegularExpressionLiteral */; } return token; - function scanRegularExpressionWorker(text2, end2, regExpFlags, isUnterminated, annexB) { - const unicodeSetsMode = !!(regExpFlags & 64 /* UnicodeSets */); - const unicodeMode = !!(regExpFlags & 96 /* UnicodeMode */); - if (unicodeMode) { - annexB = false; - } - let mayContainStrings = false; - let numberOfCapturingGroups = 0; - const groupSpecifiers = /* @__PURE__ */ new Set(); - const groupNameReferences = []; - const decimalEscapes = []; - const namedCapturingGroups = []; - function scanDisjunction(isInGroup) { - while (true) { - namedCapturingGroups.push(/* @__PURE__ */ new Set()); - scanAlternative(isInGroup); - namedCapturingGroups.pop(); - if (text2.charCodeAt(pos) !== 124 /* bar */) { - return; - } - pos++; + } + function scanRegularExpressionWorker(regExpFlags, annexB, namedCaptureGroups) { + var unicodeSetsMode = !!(regExpFlags & 64 /* UnicodeSets */); + var anyUnicodeMode = !!(regExpFlags & 96 /* AnyUnicodeMode */); + var anyUnicodeModeOrNonAnnexB = anyUnicodeMode || !annexB; + var mayContainStrings = false; + var numberOfCapturingGroups = 0; + var groupSpecifiers; + var groupNameReferences; + var decimalEscapes; + var namedCapturingGroupsScopeStack = []; + var topNamedCapturingGroupsScope; + function scanDisjunction(isInGroup) { + while (true) { + namedCapturingGroupsScopeStack.push(topNamedCapturingGroupsScope); + topNamedCapturingGroupsScope = void 0; + scanAlternative(isInGroup); + topNamedCapturingGroupsScope = namedCapturingGroupsScopeStack.pop(); + if (charCodeChecked(pos) !== 124 /* bar */) { + return; } + pos++; } - function scanAlternative(isInGroup) { - let isPreviousTermQuantifiable = false; - while (pos < end2) { - const start2 = pos; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 94 /* caret */: - case 36 /* $ */: - pos++; - isPreviousTermQuantifiable = false; - break; - case 92 /* backslash */: + } + function scanAlternative(isInGroup) { + let isPreviousTermQuantifiable = false; + while (true) { + const start2 = pos; + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 94 /* caret */: + case 36 /* $ */: + pos++; + isPreviousTermQuantifiable = false; + break; + case 92 /* backslash */: + pos++; + switch (charCodeChecked(pos)) { + case 98 /* b */: + case 66 /* B */: + pos++; + isPreviousTermQuantifiable = false; + break; + default: + scanAtomEscape(); + isPreviousTermQuantifiable = true; + break; + } + break; + case 40 /* openParen */: + pos++; + if (charCodeChecked(pos) === 63 /* question */) { pos++; - switch (text2.charCodeAt(pos)) { - case 98 /* b */: - case 66 /* B */: + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: pos++; - isPreviousTermQuantifiable = false; - break; - default: - scanAtomEscape(); - isPreviousTermQuantifiable = true; + isPreviousTermQuantifiable = !anyUnicodeModeOrNonAnnexB; break; - } - break; - case 40 /* openParen */: - pos++; - if (text2.charCodeAt(pos) === 63 /* question */) { - pos++; - switch (text2.charCodeAt(pos)) { - case 61 /* equals */: - case 33 /* exclamation */: - pos++; - isPreviousTermQuantifiable = annexB; - break; - case 60 /* lessThan */: - const groupNameStart = pos; - pos++; - switch (text2.charCodeAt(pos)) { - case 61 /* equals */: - case 33 /* exclamation */: - pos++; - isPreviousTermQuantifiable = false; - break; - default: - scanGroupName( - /*isReference*/ - false - ); - scanExpectedChar(62 /* greaterThan */); - if (languageVersion < 5 /* ES2018 */) { - error(Diagnostics.Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later, groupNameStart, pos - groupNameStart); - } - numberOfCapturingGroups++; - isPreviousTermQuantifiable = true; - break; - } - break; - default: - const start3 = pos; - const setFlags = scanPatternModifiers(0 /* None */); - if (text2.charCodeAt(pos) === 45 /* minus */) { + case 60 /* lessThan */: + const groupNameStart = pos; + pos++; + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: pos++; - scanPatternModifiers(setFlags); - if (pos === start3 + 1) { - error(Diagnostics.Subpattern_flags_must_be_present_when_there_is_a_minus_sign, start3, pos - start3); + isPreviousTermQuantifiable = false; + break; + default: + scanGroupName( + /*isReference*/ + false + ); + scanExpectedChar(62 /* greaterThan */); + if (languageVersion < 5 /* ES2018 */) { + error(Diagnostics.Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later, groupNameStart, pos - groupNameStart); } + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + break; + } + break; + default: + const start3 = pos; + const setFlags = scanPatternModifiers(0 /* None */); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + scanPatternModifiers(setFlags); + if (pos === start3 + 1) { + error(Diagnostics.Subpattern_flags_must_be_present_when_there_is_a_minus_sign, start3, pos - start3); } - scanExpectedChar(58 /* colon */); - isPreviousTermQuantifiable = true; - break; - } - } else { - numberOfCapturingGroups++; - isPreviousTermQuantifiable = true; + } + scanExpectedChar(58 /* colon */); + isPreviousTermQuantifiable = true; + break; } - scanDisjunction( - /*isInGroup*/ - true - ); - scanExpectedChar(41 /* closeParen */); + } else { + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + } + scanDisjunction( + /*isInGroup*/ + true + ); + scanExpectedChar(41 /* closeParen */); + break; + case 123 /* openBrace */: + pos++; + const digitsStart = pos; + scanDigits(); + const min2 = tokenValue; + if (!anyUnicodeModeOrNonAnnexB && !min2) { + isPreviousTermQuantifiable = true; break; - case 123 /* openBrace */: + } + if (charCodeChecked(pos) === 44 /* comma */) { pos++; - const digitsStart = pos; scanDigits(); - const min2 = tokenValue; - if (text2.charCodeAt(pos) === 44 /* comma */) { - pos++; - scanDigits(); - const max = tokenValue; - if (!min2) { - if (max || text2.charCodeAt(pos) === 125 /* closeBrace */) { - error(Diagnostics.Incomplete_quantifier_Digit_expected, digitsStart, 0); - } else { - if (unicodeMode) { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); - } - isPreviousTermQuantifiable = true; - break; - } - } - if (max && Number.parseInt(min2) > Number.parseInt(max)) { - error(Diagnostics.Numbers_out_of_order_in_quantifier, digitsStart, pos - digitsStart); - } - } else if (!min2) { - if (unicodeMode) { + const max = tokenValue; + if (!min2) { + if (max || charCodeChecked(pos) === 125 /* closeBrace */) { + error(Diagnostics.Incomplete_quantifier_Digit_expected, digitsStart, 0); + } else { error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); + isPreviousTermQuantifiable = true; + break; } - isPreviousTermQuantifiable = true; - break; - } - scanExpectedChar(125 /* closeBrace */); - pos--; - case 42 /* asterisk */: - case 43 /* plus */: - case 63 /* question */: - pos++; - if (text2.charCodeAt(pos) === 63 /* question */) { - pos++; + } else if (max && Number.parseInt(min2) > Number.parseInt(max) && (anyUnicodeModeOrNonAnnexB || charCodeChecked(pos) === 125 /* closeBrace */)) { + error(Diagnostics.Numbers_out_of_order_in_quantifier, digitsStart, pos - digitsStart); } - if (!isPreviousTermQuantifiable) { - error(Diagnostics.There_is_nothing_available_for_repetition, start2, pos - start2); + } else if (!min2) { + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); } - isPreviousTermQuantifiable = false; - break; - case 46 /* dot */: - pos++; isPreviousTermQuantifiable = true; break; - case 91 /* openBracket */: - pos++; - if (unicodeSetsMode) { - scanClassSetExpression(); + } + if (charCodeChecked(pos) !== 125 /* closeBrace */) { + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics._0_expected, pos, 0, String.fromCharCode(125 /* closeBrace */)); + pos--; } else { - scanClassRanges(); - } - scanExpectedChar(93 /* closeBracket */); - isPreviousTermQuantifiable = true; - break; - case 41 /* closeParen */: - if (isInGroup) { - return; - } - case 93 /* closeBracket */: - case 125 /* closeBrace */: - if (isUnterminated && !isInGroup) { - return; - } - if (unicodeMode || ch === 41 /* closeParen */) { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + isPreviousTermQuantifiable = true; + break; } - pos++; - isPreviousTermQuantifiable = true; - break; - case 47 /* slash */: - case 124 /* bar */: - return; - default: - scanSourceCharacter(); - isPreviousTermQuantifiable = true; - break; - } - } - } - function scanPatternModifiers(currFlags) { - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (!isIdentifierPart(ch, languageVersion)) { - break; - } - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); - if (flag === void 0) { - error(Diagnostics.Unknown_regular_expression_flag, pos, 1); - } else if (currFlags & flag) { - error(Diagnostics.Duplicate_regular_expression_flag, pos, 1); - } else if (!(flag & 28 /* Modifiers */)) { - error(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, 1); - } else { - currFlags |= flag; - const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); - if (languageVersion < availableFrom) { - error(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos, 1, getNameOfScriptTarget(availableFrom)); } - } - pos++; - } - return currFlags; - } - function scanAtomEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - switch (text2.charCodeAt(pos)) { - case 107 /* k */: + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: pos++; - if (text2.charCodeAt(pos) === 60 /* lessThan */) { + if (charCodeChecked(pos) === 63 /* question */) { pos++; - scanGroupName( - /*isReference*/ - true - ); - scanExpectedChar(62 /* greaterThan */); - } else if (unicodeMode) { - error(Diagnostics.k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets, pos - 2, 2); } - break; - case 113 /* q */: - if (unicodeSetsMode) { - pos++; - error(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); - break; + if (!isPreviousTermQuantifiable) { + error(Diagnostics.There_is_nothing_available_for_repetition, start2, pos - start2); } - default: - Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( - /*atomEscape*/ - true - )); + isPreviousTermQuantifiable = false; break; - } - } - function scanDecimalEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - const ch = text2.charCodeAt(pos); - if (ch >= 49 /* _1 */ && ch <= 57 /* _9 */) { - const start2 = pos; - scanDigits(); - decimalEscapes.push({ pos: start2, end: pos, value: +tokenValue }); - return true; - } - return false; - } - function scanCharacterEscape(atomEscape) { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - let ch = text2.charCodeAt(pos); - switch (ch) { - case 99 /* c */: + case 46 /* dot */: pos++; - ch = text2.charCodeAt(pos); - if (isASCIILetter(ch)) { - pos++; - return String.fromCharCode(ch & 31); - } - if (unicodeMode) { - error(Diagnostics.c_must_be_followed_by_an_ASCII_letter, pos - 2, 2); - } else if (atomEscape && annexB) { - pos--; - return "\\"; + isPreviousTermQuantifiable = true; + break; + case 91 /* openBracket */: + pos++; + if (unicodeSetsMode) { + scanClassSetExpression(); + } else { + scanClassRanges(); } - return String.fromCharCode(ch); - case 94 /* caret */: - case 36 /* $ */: - case 47 /* slash */: - case 92 /* backslash */: - case 46 /* dot */: - case 42 /* asterisk */: - case 43 /* plus */: - case 63 /* question */: - case 40 /* openParen */: + scanExpectedChar(93 /* closeBracket */); + isPreviousTermQuantifiable = true; + break; case 41 /* closeParen */: - case 91 /* openBracket */: + if (isInGroup) { + return; + } case 93 /* closeBracket */: - case 123 /* openBrace */: case 125 /* closeBrace */: - case 124 /* bar */: + if (anyUnicodeModeOrNonAnnexB || ch === 41 /* closeParen */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } pos++; - return String.fromCharCode(ch); + isPreviousTermQuantifiable = true; + break; + case 47 /* slash */: + case 124 /* bar */: + return; default: - if (pos >= end2) { - error(Diagnostics.Undetermined_character_escape, pos - 1, 1, ch); - return "\\"; - } - pos--; - return scanEscapeSequence( - /*shouldEmitInvalidEscapeError*/ - unicodeMode, - /*isRegularExpression*/ - annexB ? "annex-b" : true - ); + scanSourceCharacter(); + isPreviousTermQuantifiable = true; + break; } } - function scanGroupName(isReference) { - Debug.assertEqual(text2.charCodeAt(pos - 1), 60 /* lessThan */); - tokenStart = pos; - scanIdentifier(codePointAt(text2, pos), languageVersion); - if (pos === tokenStart) { - error(Diagnostics.Expected_a_capturing_group_name); - } else if (isReference) { - groupNameReferences.push({ pos: tokenStart, end: pos, name: tokenValue }); - } else if (namedCapturingGroups.some((group2) => group2.has(tokenValue))) { - error(Diagnostics.Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other, tokenStart, pos - tokenStart); + } + function scanPatternModifiers(currFlags) { + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + if (flag === void 0) { + error(Diagnostics.Unknown_regular_expression_flag, pos, 1); + } else if (currFlags & flag) { + error(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + } else if (!(flag & 28 /* Modifiers */)) { + error(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, 1); } else { - last(namedCapturingGroups).add(tokenValue); - groupSpecifiers.add(tokenValue); + currFlags |= flag; + checkRegularExpressionFlagAvailable(flag, pos); } + pos++; } - function isClassContentExit(ch) { - return ch === 93 /* closeBracket */ || pos >= end2; + return currFlags; + } + function scanAtomEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + switch (charCodeChecked(pos)) { + case 107 /* k */: + pos++; + if (charCodeChecked(pos) === 60 /* lessThan */) { + pos++; + scanGroupName( + /*isReference*/ + true + ); + scanExpectedChar(62 /* greaterThan */); + } else if (anyUnicodeModeOrNonAnnexB || namedCaptureGroups) { + error(Diagnostics.k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets, pos - 2, 2); + } + break; + case 113 /* q */: + if (unicodeSetsMode) { + pos++; + error(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); + break; + } + default: + Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( + /*atomEscape*/ + true + )); + break; + } + } + function scanDecimalEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + const ch = charCodeChecked(pos); + if (ch >= 49 /* _1 */ && ch <= 57 /* _9 */) { + const start2 = pos; + scanDigits(); + decimalEscapes = append(decimalEscapes, { pos: start2, end: pos, value: +tokenValue }); + return true; } - function scanClassRanges() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 91 /* openBracket */); - if (text2.charCodeAt(pos) === 94 /* caret */) { + return false; + } + function scanCharacterEscape(atomEscape) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + error(Diagnostics.Undetermined_character_escape, pos - 1, 1); + return "\\"; + case 99 /* c */: + pos++; + ch = charCodeChecked(pos); + if (isASCIILetter(ch)) { + pos++; + return String.fromCharCode(ch & 31); + } + if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.c_must_be_followed_by_an_ASCII_letter, pos - 2, 2); + } else if (atomEscape) { + pos--; + return "\\"; + } + return String.fromCharCode(ch); + case 94 /* caret */: + case 36 /* $ */: + case 47 /* slash */: + case 92 /* backslash */: + case 46 /* dot */: + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 124 /* bar */: pos++; + return String.fromCharCode(ch); + default: + pos--; + return scanEscapeSequence( + 4 /* RegularExpression */ | (annexB ? 8 /* AnnexB */ : 0) | (anyUnicodeMode ? 16 /* AnyUnicodeMode */ : 0) | (atomEscape ? 32 /* AtomEscape */ : 0) + ); + } + } + function scanGroupName(isReference) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 60 /* lessThan */); + tokenStart = pos; + scanIdentifier(codePointChecked(pos), languageVersion); + if (pos === tokenStart) { + error(Diagnostics.Expected_a_capturing_group_name); + } else if (isReference) { + groupNameReferences = append(groupNameReferences, { pos: tokenStart, end: pos, name: tokenValue }); + } else if ((topNamedCapturingGroupsScope == null ? void 0 : topNamedCapturingGroupsScope.has(tokenValue)) || namedCapturingGroupsScopeStack.some((group2) => group2 == null ? void 0 : group2.has(tokenValue))) { + error(Diagnostics.Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other, tokenStart, pos - tokenStart); + } else { + topNamedCapturingGroupsScope ?? (topNamedCapturingGroupsScope = /* @__PURE__ */ new Set()); + topNamedCapturingGroupsScope.add(tokenValue); + groupSpecifiers ?? (groupSpecifiers = /* @__PURE__ */ new Set()); + groupSpecifiers.add(tokenValue); + } + } + function isClassContentExit(ch) { + return ch === 93 /* closeBracket */ || ch === -1 /* EOF */ || pos >= end; + } + function scanClassRanges() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + } + while (true) { + const ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; } - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { + const minStart = pos; + const minCharacter = scanClassAtom(); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + const ch2 = charCodeChecked(pos); + if (isClassContentExit(ch2)) { return; } - const minStart = pos; - const minCharacter = scanClassAtom(); - if (text2.charCodeAt(pos) === 45 /* minus */) { - pos++; - const ch2 = text2.charCodeAt(pos); - if (isClassContentExit(ch2)) { - return; + if (!minCharacter && anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, minStart, pos - 1 - minStart); + } + const maxStart = pos; + const maxCharacter = scanClassAtom(); + if (!maxCharacter && anyUnicodeModeOrNonAnnexB) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, maxStart, pos - maxStart); + continue; + } + if (!minCharacter) { + continue; + } + const minCharacterValue = codePointAt(minCharacter, 0); + const maxCharacterValue = codePointAt(maxCharacter, 0); + if (minCharacter.length === charSize(minCharacterValue) && maxCharacter.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error(Diagnostics.Range_out_of_order_in_character_class, minStart, pos - minStart); + } + } + } + } + function scanClassSetExpression() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + let isCharacterComplement = false; + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + isCharacterComplement = true; + } + let expressionMayContainStrings = false; + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; + } + let start2 = pos; + let operand; + switch (text.slice(pos, pos + 2)) { + case "--": + case "&&": + error(Diagnostics.Expected_a_class_set_operand); + mayContainStrings = false; + break; + default: + operand = scanClassSetOperand(); + break; + } + switch (charCodeChecked(pos)) { + case 45 /* minus */: + if (charCodeChecked(pos + 1) === 45 /* minus */) { + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); } - if (!minCharacter && !annexB) { - error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, minStart, pos - 1 - minStart); + expressionMayContainStrings = mayContainStrings; + scanClassSetSubExpression(3 /* ClassSubtraction */); + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } + break; + case 38 /* ampersand */: + if (charCodeChecked(pos + 1) === 38 /* ampersand */) { + scanClassSetSubExpression(2 /* ClassIntersection */); + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); } - const maxStart = pos; - const maxCharacter = scanClassAtom(); - if (!maxCharacter && !annexB) { - error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, maxStart, pos - maxStart); - continue; + expressionMayContainStrings = mayContainStrings; + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } + break; + default: + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + } + expressionMayContainStrings = mayContainStrings; + break; + } + while (true) { + ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + break; + } + switch (ch) { + case 45 /* minus */: + pos++; + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; } - if (!minCharacter) { + if (ch === 45 /* minus */) { + pos++; + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + start2 = pos - 2; + operand = text.slice(start2, pos); continue; + } else { + if (!operand) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, start2, pos - 1 - start2); + } + const secondStart = pos; + const secondOperand = scanClassSetOperand(); + if (isCharacterComplement && mayContainStrings) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, secondStart, pos - secondStart); + } + expressionMayContainStrings || (expressionMayContainStrings = mayContainStrings); + if (!secondOperand) { + error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, secondStart, pos - secondStart); + break; + } + if (!operand) { + break; + } + const minCharacterValue = codePointAt(operand, 0); + const maxCharacterValue = codePointAt(secondOperand, 0); + if (operand.length === charSize(minCharacterValue) && secondOperand.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error(Diagnostics.Range_out_of_order_in_character_class, start2, pos - start2); + } } - const minCharacterValue = codePointAt(minCharacter, 0); - const maxCharacterValue = codePointAt(maxCharacter, 0); - if (minCharacter.length === charSize(minCharacterValue) && maxCharacter.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { - error(Diagnostics.Range_out_of_order_in_character_class, minStart, pos - minStart); + break; + case 38 /* ampersand */: + start2 = pos; + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + if (charCodeChecked(pos) === 38 /* ampersand */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; + } + } else { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); } - } - } - } - function scanClassSetExpression() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 91 /* openBracket */); - let isCharacterComplement = false; - if (text2.charCodeAt(pos) === 94 /* caret */) { - pos++; - isCharacterComplement = true; + operand = text.slice(start2, pos); + continue; } - let expressionMayContainStrings = false; - let ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - return; + if (isClassContentExit(charCodeChecked(pos))) { + break; } - let start2 = pos; - let oprand; - switch (text2.slice(pos, pos + 2)) { + start2 = pos; + switch (text.slice(pos, pos + 2)) { case "--": case "&&": - error(Diagnostics.Expected_a_class_set_oprand); - mayContainStrings = false; + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); + pos += 2; + operand = text.slice(start2, pos); break; default: - oprand = scanClassSetOprand(); + operand = scanClassSetOperand(); break; } - switch (text2.charCodeAt(pos)) { + } + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + } + function scanClassSetSubExpression(expressionType) { + let expressionMayContainStrings = mayContainStrings; + while (true) { + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + break; + } + switch (ch) { case 45 /* minus */: - if (text2.charCodeAt(pos + 1) === 45 /* minus */) { - if (isCharacterComplement && mayContainStrings) { - error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + pos++; + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + if (expressionType !== 3 /* ClassSubtraction */) { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); } - expressionMayContainStrings = mayContainStrings; - scanClassSetSubExpression(3 /* ClassSubtraction */); - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; + } else { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 1, 1); } break; case 38 /* ampersand */: - if (text2.charCodeAt(pos + 1) === 38 /* ampersand */) { - scanClassSetSubExpression(2 /* ClassIntersection */); - if (isCharacterComplement && mayContainStrings) { - error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + if (expressionType !== 2 /* ClassIntersection */) { + error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + } + if (charCodeChecked(pos) === 38 /* ampersand */) { + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; } - expressionMayContainStrings = mayContainStrings; - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; } else { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); } break; default: - if (isCharacterComplement && mayContainStrings) { - error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + switch (expressionType) { + case 3 /* ClassSubtraction */: + error(Diagnostics._0_expected, pos, 0, "--"); + break; + case 2 /* ClassIntersection */: + error(Diagnostics._0_expected, pos, 0, "&&"); + break; + default: + break; } - expressionMayContainStrings = mayContainStrings; break; } - while (pos < end2) { - ch = text2.charCodeAt(pos); - switch (ch) { - case 45 /* minus */: - pos++; - ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; - } - if (ch === 45 /* minus */) { - pos++; - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - start2 = pos - 2; - oprand = text2.slice(start2, pos); - continue; - } else { - if (!oprand) { - error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, start2, pos - 1 - start2); - } - const secondStart = pos; - const secondOprand = scanClassSetOprand(); - if (isCharacterComplement && mayContainStrings) { - error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, secondStart, pos - secondStart); - } - expressionMayContainStrings || (expressionMayContainStrings = mayContainStrings); - if (!secondOprand) { - error(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, secondStart, pos - secondStart); - break; - } - if (!oprand) { - break; - } - const minCharacterValue = codePointAt(oprand, 0); - const maxCharacterValue = codePointAt(secondOprand, 0); - if (oprand.length === charSize(minCharacterValue) && secondOprand.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { - error(Diagnostics.Range_out_of_order_in_character_class, start2, pos - start2); - } - } - break; - case 38 /* ampersand */: - start2 = pos; - pos++; - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - pos++; - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); - pos++; - } - } else { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); - } - oprand = text2.slice(start2, pos); - continue; - } - if (isClassContentExit(text2.charCodeAt(pos))) { - break; - } - start2 = pos; - switch (text2.slice(pos, pos + 2)) { - case "--": - case "&&": - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); - pos += 2; - oprand = text2.slice(start2, pos); - break; - default: - oprand = scanClassSetOprand(); - break; - } + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + error(Diagnostics.Expected_a_class_set_operand); + break; } - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + scanClassSetOperand(); + expressionMayContainStrings && (expressionMayContainStrings = mayContainStrings); } - function scanClassSetSubExpression(expressionType) { - let expressionMayContainStrings = mayContainStrings; - while (pos < end2) { - let ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - break; - } - switch (ch) { - case 45 /* minus */: - pos++; - if (text2.charCodeAt(pos) === 45 /* minus */) { - pos++; - if (expressionType !== 3 /* ClassSubtraction */) { - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - } - } else { - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 1, 1); - } - break; - case 38 /* ampersand */: + mayContainStrings = expressionMayContainStrings; + } + function scanClassSetOperand() { + mayContainStrings = false; + switch (charCodeChecked(pos)) { + case -1 /* EOF */: + return ""; + case 91 /* openBracket */: + pos++; + scanClassSetExpression(); + scanExpectedChar(93 /* closeBracket */); + return ""; + case 92 /* backslash */: + pos++; + if (scanCharacterClassEscape()) { + return ""; + } else if (charCodeChecked(pos) === 113 /* q */) { + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { pos++; - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - pos++; - if (expressionType !== 2 /* ClassIntersection */) { - error(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - } - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); - pos++; - } - } else { - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); - } - break; - default: - switch (expressionType) { - case 3 /* ClassSubtraction */: - error(Diagnostics._0_expected, pos, 0, "--"); - break; - case 2 /* ClassIntersection */: - error(Diagnostics._0_expected, pos, 0, "&&"); - break; - default: - break; - } - break; + scanClassStringDisjunctionContents(); + scanExpectedChar(125 /* closeBrace */); + return ""; + } else { + error(Diagnostics.q_must_be_followed_by_string_alternatives_enclosed_in_braces, pos - 2, 2); + return "q"; + } } - ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - error(Diagnostics.Expected_a_class_set_oprand); + pos--; + default: + return scanClassSetCharacter(); + } + } + function scanClassStringDisjunctionContents() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 123 /* openBrace */); + let characterCount = 0; + while (true) { + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 125 /* closeBrace */: + if (characterCount !== 1) { + mayContainStrings = true; + } + return; + case 124 /* bar */: + if (characterCount !== 1) { + mayContainStrings = true; + } + pos++; + start = pos; + characterCount = 0; + break; + default: + scanClassSetCharacter(); + characterCount++; break; - } - scanClassSetOprand(); - expressionMayContainStrings && (expressionMayContainStrings = mayContainStrings); } - mayContainStrings = expressionMayContainStrings; } - function scanClassSetOprand() { - mayContainStrings = false; - switch (text2.charCodeAt(pos)) { - case 91 /* openBracket */: + } + function scanClassSetCharacter() { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + return ""; + } + if (ch === 92 /* backslash */) { + pos++; + const ch2 = charCodeChecked(pos); + switch (ch2) { + case 98 /* b */: pos++; - scanClassSetExpression(); - scanExpectedChar(93 /* closeBracket */); - return ""; - case 92 /* backslash */: + return "\b"; + case 38 /* ampersand */: + case 45 /* minus */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 44 /* comma */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: pos++; - if (scanCharacterClassEscape()) { - return ""; - } else if (text2.charCodeAt(pos) === 113 /* q */) { - pos++; - if (text2.charCodeAt(pos) === 123 /* openBrace */) { - pos++; - scanClassStringDisjunctionContents(); - scanExpectedChar(125 /* closeBrace */); - return ""; - } else { - error(Diagnostics.q_must_be_followed_by_string_alternatives_enclosed_in_braces, pos - 2, 2); - return "q"; - } - } - pos--; + return String.fromCharCode(ch2); default: - return scanClassSetCharacter(); - } - } - function scanClassStringDisjunctionContents() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 123 /* openBrace */); - let characterCount = 0; - while (pos < end2) { - const ch = text2.charCodeAt(pos); - switch (ch) { - case 125 /* closeBrace */: - if (characterCount !== 1) { - mayContainStrings = true; - } - return; - case 124 /* bar */: - if (characterCount !== 1) { - mayContainStrings = true; - } - pos++; - start = pos; - characterCount = 0; - break; - default: - scanClassSetCharacter(); - characterCount++; - break; - } + return scanCharacterEscape( + /*atomEscape*/ + false + ); + } + } else if (ch === charCodeChecked(pos + 1)) { + switch (ch) { + case 38 /* ampersand */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 42 /* asterisk */: + case 43 /* plus */: + case 44 /* comma */: + case 46 /* dot */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 63 /* question */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: + error(Diagnostics.A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash, pos, 2); + pos += 2; + return text.substring(pos - 2, pos); } } - function scanClassSetCharacter() { - const ch = text2.charCodeAt(pos); - if (ch === 92 /* backslash */) { + switch (ch) { + case 47 /* slash */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 45 /* minus */: + case 124 /* bar */: + error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); pos++; - const ch2 = text2.charCodeAt(pos); - switch (ch2) { - case 98 /* b */: - pos++; - return "\b"; - case 38 /* ampersand */: - case 45 /* minus */: - case 33 /* exclamation */: - case 35 /* hash */: - case 37 /* percent */: - case 44 /* comma */: - case 58 /* colon */: - case 59 /* semicolon */: - case 60 /* lessThan */: - case 61 /* equals */: - case 62 /* greaterThan */: - case 64 /* at */: - case 96 /* backtick */: - case 126 /* tilde */: - pos++; - return String.fromCharCode(ch2); - default: - return scanCharacterEscape( - /*atomEscape*/ - false - ); - } - } else if (ch === text2.charCodeAt(pos + 1)) { - switch (ch) { - case 38 /* ampersand */: - case 33 /* exclamation */: - case 35 /* hash */: - case 37 /* percent */: - case 42 /* asterisk */: - case 43 /* plus */: - case 44 /* comma */: - case 46 /* dot */: - case 58 /* colon */: - case 59 /* semicolon */: - case 60 /* lessThan */: - case 61 /* equals */: - case 62 /* greaterThan */: - case 63 /* question */: - case 64 /* at */: - case 96 /* backtick */: - case 126 /* tilde */: - error(Diagnostics.A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash, pos, 2); - pos += 2; - return text2.substring(pos - 2, pos); - } - } + return String.fromCharCode(ch); + } + return scanSourceCharacter(); + } + function scanClassAtom() { + if (charCodeChecked(pos) === 92 /* backslash */) { + pos++; + const ch = charCodeChecked(pos); switch (ch) { - case 47 /* slash */: - case 40 /* openParen */: - case 41 /* closeParen */: - case 91 /* openBracket */: - case 93 /* closeBracket */: - case 123 /* openBrace */: - case 125 /* closeBrace */: + case 98 /* b */: + pos++; + return "\b"; case 45 /* minus */: - case 124 /* bar */: - error(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); pos++; return String.fromCharCode(ch); + default: + if (scanCharacterClassEscape()) { + return ""; + } + return scanCharacterEscape( + /*atomEscape*/ + false + ); } + } else { return scanSourceCharacter(); } - function scanClassAtom() { - if (text2.charCodeAt(pos) === 92 /* backslash */) { + } + function scanCharacterClassEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let isCharacterComplement = false; + const start2 = pos - 1; + const ch = charCodeChecked(pos); + switch (ch) { + case 100 /* d */: + case 68 /* D */: + case 115 /* s */: + case 83 /* S */: + case 119 /* w */: + case 87 /* W */: pos++; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 98 /* b */: - pos++; - return "\b"; - case 45 /* minus */: - pos++; - return String.fromCharCode(ch); - default: - if (scanCharacterClassEscape()) { - return ""; - } - return scanCharacterEscape( - /*atomEscape*/ - false - ); - } - } else { - return scanSourceCharacter(); - } - } - function scanCharacterClassEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - let isCharacterComplement = false; - const start2 = pos - 1; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 100 /* d */: - case 68 /* D */: - case 115 /* s */: - case 83 /* S */: - case 119 /* w */: - case 87 /* W */: - pos++; - return true; - case 80 /* P */: - isCharacterComplement = true; - case 112 /* p */: + return true; + case 80 /* P */: + isCharacterComplement = true; + case 112 /* p */: + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { pos++; - if (text2.charCodeAt(pos) === 123 /* openBrace */) { + const propertyNameOrValueStart = pos; + const propertyNameOrValue = scanWordCharacters(); + if (charCodeChecked(pos) === 61 /* equals */) { + const propertyName = nonBinaryUnicodeProperties.get(propertyNameOrValue); + if (pos === propertyNameOrValueStart) { + error(Diagnostics.Expected_a_Unicode_property_name); + } else if (propertyName === void 0) { + error(Diagnostics.Unknown_Unicode_property_name, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, nonBinaryUnicodeProperties.keys(), identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); + } + } pos++; - const propertyNameOrValueStart = pos; - const propertyNameOrValue = scanWordCharacters(); - if (text2.charCodeAt(pos) === 61 /* equals */) { - const propertyName = nonBinaryUnicodeProperties.get(propertyNameOrValue); - if (pos === propertyNameOrValueStart) { - error(Diagnostics.Expected_a_Unicode_property_name); - } else if (propertyName === void 0) { - error(Diagnostics.Unknown_Unicode_property_name, propertyNameOrValueStart, pos - propertyNameOrValueStart); - const suggestion = getSpellingSuggestion(propertyNameOrValue, nonBinaryUnicodeProperties.keys(), identity); - if (suggestion) { - error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); - } + const propertyValueStart = pos; + const propertyValue = scanWordCharacters(); + if (pos === propertyValueStart) { + error(Diagnostics.Expected_a_Unicode_property_value); + } else if (propertyName !== void 0 && !valuesOfNonBinaryUnicodeProperties[propertyName].has(propertyValue)) { + error(Diagnostics.Unknown_Unicode_property_value, propertyValueStart, pos - propertyValueStart); + const suggestion = getSpellingSuggestion(propertyValue, valuesOfNonBinaryUnicodeProperties[propertyName], identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyValueStart, pos - propertyValueStart, suggestion); } - pos++; - const propertyValueStart = pos; - const propertyValue = scanWordCharacters(); - if (pos === propertyValueStart) { - error(Diagnostics.Expected_a_Unicode_property_value); - } else if (propertyName !== void 0 && !valuesOfNonBinaryUnicodeProperties[propertyName].has(propertyValue)) { - error(Diagnostics.Unknown_Unicode_property_value, propertyValueStart, pos - propertyValueStart); - const suggestion = getSpellingSuggestion(propertyValue, valuesOfNonBinaryUnicodeProperties[propertyName], identity); - if (suggestion) { - error(Diagnostics.Did_you_mean_0, propertyValueStart, pos - propertyValueStart, suggestion); - } + } + } else { + if (pos === propertyNameOrValueStart) { + error(Diagnostics.Expected_a_Unicode_property_name_or_value); + } else if (binaryUnicodePropertiesOfStrings.has(propertyNameOrValue)) { + if (!unicodeSetsMode) { + error(Diagnostics.Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else if (isCharacterComplement) { + error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else { + mayContainStrings = true; } - } else { - if (pos === propertyNameOrValueStart) { - error(Diagnostics.Expected_a_Unicode_property_name_or_value); - } else if (binaryUnicodePropertiesOfStrings.has(propertyNameOrValue)) { - if (!unicodeSetsMode) { - error(Diagnostics.Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set, propertyNameOrValueStart, pos - propertyNameOrValueStart); - } else if (isCharacterComplement) { - error(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, propertyNameOrValueStart, pos - propertyNameOrValueStart); - } else { - mayContainStrings = true; - } - } else if (!valuesOfNonBinaryUnicodeProperties.General_Category.has(propertyNameOrValue) && !binaryUnicodeProperties.has(propertyNameOrValue)) { - error(Diagnostics.Unknown_Unicode_property_name_or_value, propertyNameOrValueStart, pos - propertyNameOrValueStart); - const suggestion = getSpellingSuggestion(propertyNameOrValue, [...valuesOfNonBinaryUnicodeProperties.General_Category, ...binaryUnicodeProperties, ...binaryUnicodePropertiesOfStrings], identity); - if (suggestion) { - error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); - } + } else if (!valuesOfNonBinaryUnicodeProperties.General_Category.has(propertyNameOrValue) && !binaryUnicodeProperties.has(propertyNameOrValue)) { + error(Diagnostics.Unknown_Unicode_property_name_or_value, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, [...valuesOfNonBinaryUnicodeProperties.General_Category, ...binaryUnicodeProperties, ...binaryUnicodePropertiesOfStrings], identity); + if (suggestion) { + error(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); } } - scanExpectedChar(125 /* closeBrace */); - if (!unicodeMode) { - error(Diagnostics.Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); - } - } else if (unicodeMode) { - error(Diagnostics._0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces, pos - 2, 2, String.fromCharCode(ch)); } - return true; - } - return false; - } - function scanWordCharacters() { - let value = ""; - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (!isWordCharacter(ch)) { - break; + scanExpectedChar(125 /* closeBrace */); + if (!anyUnicodeMode) { + error(Diagnostics.Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); + } + } else if (anyUnicodeModeOrNonAnnexB) { + error(Diagnostics._0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces, pos - 2, 2, String.fromCharCode(ch)); + } else { + pos--; + return false; } - value += String.fromCharCode(ch); - pos++; + return true; + } + return false; + } + function scanWordCharacters() { + let value = ""; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isWordCharacter(ch)) { + break; } - return value; + value += String.fromCharCode(ch); + pos++; } - function scanSourceCharacter() { - const size = unicodeMode ? charSize(codePointAt(text2, pos)) : 1; - pos += size; - return text2.substring(pos - size, pos); + return value; + } + function scanSourceCharacter() { + const size = anyUnicodeMode ? charSize(charCodeChecked(pos)) : 1; + pos += size; + return size > 0 ? text.substring(pos - size, pos) : ""; + } + function scanExpectedChar(ch) { + if (charCodeChecked(pos) === ch) { + pos++; + } else { + error(Diagnostics._0_expected, pos, 0, String.fromCharCode(ch)); } - function scanExpectedChar(ch) { - if (text2.charCodeAt(pos) === ch) { - pos++; + } + scanDisjunction( + /*isInGroup*/ + false + ); + forEach(groupNameReferences, (reference) => { + if (!(groupSpecifiers == null ? void 0 : groupSpecifiers.has(reference.name))) { + error(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); + } + }); + forEach(decimalEscapes, (escape) => { + if (escape.value > numberOfCapturingGroups) { + if (numberOfCapturingGroups) { + error(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos, numberOfCapturingGroups); } else { - error(Diagnostics._0_expected, pos, 0, String.fromCharCode(ch)); + error(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos); } } - scanDisjunction( - /*isInGroup*/ - false - ); - forEach(groupNameReferences, (reference) => { - if (!groupSpecifiers.has(reference.name)) { - error(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); - } - }); - forEach(decimalEscapes, (escape) => { - if (!annexB && escape.value > numberOfCapturingGroups) { - if (numberOfCapturingGroups) { - error(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos, numberOfCapturingGroups); - } else { - error(Diagnostics.This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups, escape.pos, escape.end - escape.pos); - } - } - }); + }); + } + function checkRegularExpressionFlagAvailable(flag, pos2) { + const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); + if (availableFrom && languageVersion < availableFrom) { + error(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos2, 1, getNameOfScriptTarget(availableFrom)); } } function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { @@ -10750,9 +10729,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - let char = text.charCodeAt(pos); + let char = charCodeUnchecked(pos); if (char === 60 /* lessThan */) { - if (text.charCodeAt(pos + 1) === 47 /* slash */) { + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; return token = 31 /* LessThanSlashToken */; } @@ -10765,7 +10744,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } let firstNonWhitespace = 0; while (pos < end) { - char = text.charCodeAt(pos); + char = charCodeUnchecked(pos); if (char === 123 /* openBrace */) { break; } @@ -10797,7 +10776,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { while (pos < end) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 45 /* minus */) { tokenValue += "-"; pos++; @@ -10815,7 +10794,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function scanJsxAttributeValue() { fullStartPos = pos; - switch (text.charCodeAt(pos)) { + switch (charCodeUnchecked(pos)) { case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString( @@ -10837,11 +10816,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - for (let ch = text.charCodeAt(pos); pos < end && (!isLineBreak(ch) && ch !== 96 /* backtick */); ch = codePointAt(text, ++pos)) { + for (let ch = charCodeUnchecked(pos); pos < end && (!isLineBreak(ch) && ch !== 96 /* backtick */); ch = codePointUnchecked(++pos)) { if (!inBackticks) { if (ch === 123 /* openBrace */) { break; - } else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(text.charCodeAt(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(text.charCodeAt(pos + 1)))) { + } else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(charCodeUnchecked(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(charCodeUnchecked(pos + 1)))) { break; } } @@ -10858,21 +10837,21 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); pos += charSize(ch); switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: - while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { pos++; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: return token = 60 /* AtToken */; case 13 /* carriageReturn */: - if (text.charCodeAt(pos) === 10 /* lineFeed */) { + if (charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } case 10 /* lineFeed */: @@ -10928,8 +10907,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (isIdentifierStart(ch, languageVersion)) { let char = ch; - while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */) - pos += charSize(char); + while (pos < end && isIdentifierPart(char = codePointUnchecked(pos), languageVersion) || char === 45 /* minus */) pos += charSize(char); tokenValue = text.substring(tokenStart, pos); if (char === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -11038,6 +11016,9 @@ function charSize(ch) { if (ch >= 65536) { return 2; } + if (ch === -1 /* EOF */) { + return 0; + } return 1; } function utf16EncodeAsStringFallback(codePoint) { @@ -11065,17 +11046,17 @@ var binaryUnicodeProperties = /* @__PURE__ */ new Set(["ASCII", "ASCII_Hex_Digit var binaryUnicodePropertiesOfStrings = /* @__PURE__ */ new Set(["Basic_Emoji", "Emoji_Keycap_Sequence", "RGI_Emoji_Modifier_Sequence", "RGI_Emoji_Flag_Sequence", "RGI_Emoji_Tag_Sequence", "RGI_Emoji_ZWJ_Sequence", "RGI_Emoji"]); var valuesOfNonBinaryUnicodeProperties = { General_Category: /* @__PURE__ */ new Set(["C", "Other", "Cc", "Control", "cntrl", "Cf", "Format", "Cn", "Unassigned", "Co", "Private_Use", "Cs", "Surrogate", "L", "Letter", "LC", "Cased_Letter", "Ll", "Lowercase_Letter", "Lm", "Modifier_Letter", "Lo", "Other_Letter", "Lt", "Titlecase_Letter", "Lu", "Uppercase_Letter", "M", "Mark", "Combining_Mark", "Mc", "Spacing_Mark", "Me", "Enclosing_Mark", "Mn", "Nonspacing_Mark", "N", "Number", "Nd", "Decimal_Number", "digit", "Nl", "Letter_Number", "No", "Other_Number", "P", "Punctuation", "punct", "Pc", "Connector_Punctuation", "Pd", "Dash_Punctuation", "Pe", "Close_Punctuation", "Pf", "Final_Punctuation", "Pi", "Initial_Punctuation", "Po", "Other_Punctuation", "Ps", "Open_Punctuation", "S", "Symbol", "Sc", "Currency_Symbol", "Sk", "Modifier_Symbol", "Sm", "Math_Symbol", "So", "Other_Symbol", "Z", "Separator", "Zl", "Line_Separator", "Zp", "Paragraph_Separator", "Zs", "Space_Separator"]), - Script: /* @__PURE__ */ new Set(["Adlm", "Adlam", "Aghb", "Caucasian_Albanian", "Ahom", "Ahom", "Arab", "Arabic", "Armi", "Imperial_Aramaic", "Armn", "Armenian", "Avst", "Avestan", "Bali", "Balinese", "Bamu", "Bamum", "Bass", "Bassa_Vah", "Batk", "Batak", "Beng", "Bengali", "Bhks", "Bhaiksuki", "Bopo", "Bopomofo", "Brah", "Brahmi", "Brai", "Braille", "Bugi", "Buginese", "Buhd", "Buhid", "Cakm", "Chakma", "Cans", "Canadian_Aboriginal", "Cari", "Carian", "Cham", "Cham", "Cher", "Cherokee", "Chrs", "Chorasmian", "Copt", "Coptic", "Qaac", "Cpmn", "Cypro_Minoan", "Cprt", "Cypriot", "Cyrl", "Cyrillic", "Deva", "Devanagari", "Diak", "Dives_Akuru", "Dogr", "Dogra", "Dsrt", "Deseret", "Dupl", "Duployan", "Egyp", "Egyptian_Hieroglyphs", "Elba", "Elbasan", "Elym", "Elymaic", "Ethi", "Ethiopic", "Geor", "Georgian", "Glag", "Glagolitic", "Gong", "Gunjala_Gondi", "Gonm", "Masaram_Gondi", "Goth", "Gothic", "Gran", "Grantha", "Grek", "Greek", "Gujr", "Gujarati", "Guru", "Gurmukhi", "Hang", "Hangul", "Hani", "Han", "Hano", "Hanunoo", "Hatr", "Hatran", "Hebr", "Hebrew", "Hira", "Hiragana", "Hluw", "Anatolian_Hieroglyphs", "Hmng", "Pahawh_Hmong", "Hmnp", "Nyiakeng_Puachue_Hmong", "Hrkt", "Katakana_Or_Hiragana", "Hung", "Old_Hungarian", "Ital", "Old_Italic", "Java", "Javanese", "Kali", "Kayah_Li", "Kana", "Katakana", "Kawi", "Kawi", "Khar", "Kharoshthi", "Khmr", "Khmer", "Khoj", "Khojki", "Kits", "Khitan_Small_Script", "Knda", "Kannada", "Kthi", "Kaithi", "Lana", "Tai_Tham", "Laoo", "Lao", "Latn", "Latin", "Lepc", "Lepcha", "Limb", "Limbu", "Lina", "Linear_A", "Linb", "Linear_B", "Lisu", "Lisu", "Lyci", "Lycian", "Lydi", "Lydian", "Mahj", "Mahajani", "Maka", "Makasar", "Mand", "Mandaic", "Mani", "Manichaean", "Marc", "Marchen", "Medf", "Medefaidrin", "Mend", "Mende_Kikakui", "Merc", "Meroitic_Cursive", "Mero", "Meroitic_Hieroglyphs", "Mlym", "Malayalam", "Modi", "Modi", "Mong", "Mongolian", "Mroo", "Mro", "Mtei", "Meetei_Mayek", "Mult", "Multani", "Mymr", "Myanmar", "Nagm", "Nag_Mundari", "Nand", "Nandinagari", "Narb", "Old_North_Arabian", "Nbat", "Nabataean", "Newa", "Newa", "Nkoo", "Nko", "Nshu", "Nushu", "Ogam", "Ogham", "Olck", "Ol_Chiki", "Orkh", "Old_Turkic", "Orya", "Oriya", "Osge", "Osage", "Osma", "Osmanya", "Ougr", "Old_Uyghur", "Palm", "Palmyrene", "Pauc", "Pau_Cin_Hau", "Perm", "Old_Permic", "Phag", "Phags_Pa", "Phli", "Inscriptional_Pahlavi", "Phlp", "Psalter_Pahlavi", "Phnx", "Phoenician", "Plrd", "Miao", "Prti", "Inscriptional_Parthian", "Rjng", "Rejang", "Rohg", "Hanifi_Rohingya", "Runr", "Runic", "Samr", "Samaritan", "Sarb", "Old_South_Arabian", "Saur", "Saurashtra", "Sgnw", "SignWriting", "Shaw", "Shavian", "Shrd", "Sharada", "Sidd", "Siddham", "Sind", "Khudawadi", "Sinh", "Sinhala", "Sogd", "Sogdian", "Sogo", "Old_Sogdian", "Sora", "Sora_Sompeng", "Soyo", "Soyombo", "Sund", "Sundanese", "Sylo", "Syloti_Nagri", "Syrc", "Syriac", "Tagb", "Tagbanwa", "Takr", "Takri", "Tale", "Tai_Le", "Talu", "New_Tai_Lue", "Taml", "Tamil", "Tang", "Tangut", "Tavt", "Tai_Viet", "Telu", "Telugu", "Tfng", "Tifinagh", "Tglg", "Tagalog", "Thaa", "Thaana", "Thai", "Thai", "Tibt", "Tibetan", "Tirh", "Tirhuta", "Tnsa", "Tangsa", "Toto", "Toto", "Ugar", "Ugaritic", "Vaii", "Vai", "Vith", "Vithkuqi", "Wara", "Warang_Citi", "Wcho", "Wancho", "Xpeo", "Old_Persian", "Xsux", "Cuneiform", "Yezi", "Yezidi", "Yiii", "Yi", "Zanb", "Zanabazar_Square", "Zinh", "Inherited", "Qaai", "Zyyy", "Common", "Zzzz", "Unknown"]), - Script_Extensions: /* @__PURE__ */ new Set() - // Currently empty + Script: /* @__PURE__ */ new Set(["Adlm", "Adlam", "Aghb", "Caucasian_Albanian", "Ahom", "Arab", "Arabic", "Armi", "Imperial_Aramaic", "Armn", "Armenian", "Avst", "Avestan", "Bali", "Balinese", "Bamu", "Bamum", "Bass", "Bassa_Vah", "Batk", "Batak", "Beng", "Bengali", "Bhks", "Bhaiksuki", "Bopo", "Bopomofo", "Brah", "Brahmi", "Brai", "Braille", "Bugi", "Buginese", "Buhd", "Buhid", "Cakm", "Chakma", "Cans", "Canadian_Aboriginal", "Cari", "Carian", "Cham", "Cher", "Cherokee", "Chrs", "Chorasmian", "Copt", "Coptic", "Qaac", "Cpmn", "Cypro_Minoan", "Cprt", "Cypriot", "Cyrl", "Cyrillic", "Deva", "Devanagari", "Diak", "Dives_Akuru", "Dogr", "Dogra", "Dsrt", "Deseret", "Dupl", "Duployan", "Egyp", "Egyptian_Hieroglyphs", "Elba", "Elbasan", "Elym", "Elymaic", "Ethi", "Ethiopic", "Geor", "Georgian", "Glag", "Glagolitic", "Gong", "Gunjala_Gondi", "Gonm", "Masaram_Gondi", "Goth", "Gothic", "Gran", "Grantha", "Grek", "Greek", "Gujr", "Gujarati", "Guru", "Gurmukhi", "Hang", "Hangul", "Hani", "Han", "Hano", "Hanunoo", "Hatr", "Hatran", "Hebr", "Hebrew", "Hira", "Hiragana", "Hluw", "Anatolian_Hieroglyphs", "Hmng", "Pahawh_Hmong", "Hmnp", "Nyiakeng_Puachue_Hmong", "Hrkt", "Katakana_Or_Hiragana", "Hung", "Old_Hungarian", "Ital", "Old_Italic", "Java", "Javanese", "Kali", "Kayah_Li", "Kana", "Katakana", "Kawi", "Khar", "Kharoshthi", "Khmr", "Khmer", "Khoj", "Khojki", "Kits", "Khitan_Small_Script", "Knda", "Kannada", "Kthi", "Kaithi", "Lana", "Tai_Tham", "Laoo", "Lao", "Latn", "Latin", "Lepc", "Lepcha", "Limb", "Limbu", "Lina", "Linear_A", "Linb", "Linear_B", "Lisu", "Lyci", "Lycian", "Lydi", "Lydian", "Mahj", "Mahajani", "Maka", "Makasar", "Mand", "Mandaic", "Mani", "Manichaean", "Marc", "Marchen", "Medf", "Medefaidrin", "Mend", "Mende_Kikakui", "Merc", "Meroitic_Cursive", "Mero", "Meroitic_Hieroglyphs", "Mlym", "Malayalam", "Modi", "Mong", "Mongolian", "Mroo", "Mro", "Mtei", "Meetei_Mayek", "Mult", "Multani", "Mymr", "Myanmar", "Nagm", "Nag_Mundari", "Nand", "Nandinagari", "Narb", "Old_North_Arabian", "Nbat", "Nabataean", "Newa", "Nkoo", "Nko", "Nshu", "Nushu", "Ogam", "Ogham", "Olck", "Ol_Chiki", "Orkh", "Old_Turkic", "Orya", "Oriya", "Osge", "Osage", "Osma", "Osmanya", "Ougr", "Old_Uyghur", "Palm", "Palmyrene", "Pauc", "Pau_Cin_Hau", "Perm", "Old_Permic", "Phag", "Phags_Pa", "Phli", "Inscriptional_Pahlavi", "Phlp", "Psalter_Pahlavi", "Phnx", "Phoenician", "Plrd", "Miao", "Prti", "Inscriptional_Parthian", "Rjng", "Rejang", "Rohg", "Hanifi_Rohingya", "Runr", "Runic", "Samr", "Samaritan", "Sarb", "Old_South_Arabian", "Saur", "Saurashtra", "Sgnw", "SignWriting", "Shaw", "Shavian", "Shrd", "Sharada", "Sidd", "Siddham", "Sind", "Khudawadi", "Sinh", "Sinhala", "Sogd", "Sogdian", "Sogo", "Old_Sogdian", "Sora", "Sora_Sompeng", "Soyo", "Soyombo", "Sund", "Sundanese", "Sylo", "Syloti_Nagri", "Syrc", "Syriac", "Tagb", "Tagbanwa", "Takr", "Takri", "Tale", "Tai_Le", "Talu", "New_Tai_Lue", "Taml", "Tamil", "Tang", "Tangut", "Tavt", "Tai_Viet", "Telu", "Telugu", "Tfng", "Tifinagh", "Tglg", "Tagalog", "Thaa", "Thaana", "Thai", "Tibt", "Tibetan", "Tirh", "Tirhuta", "Tnsa", "Tangsa", "Toto", "Ugar", "Ugaritic", "Vaii", "Vai", "Vith", "Vithkuqi", "Wara", "Warang_Citi", "Wcho", "Wancho", "Xpeo", "Old_Persian", "Xsux", "Cuneiform", "Yezi", "Yezidi", "Yiii", "Yi", "Zanb", "Zanabazar_Square", "Zinh", "Inherited", "Qaai", "Zyyy", "Common", "Zzzz", "Unknown"]), + Script_Extensions: void 0 }; +valuesOfNonBinaryUnicodeProperties.Script_Extensions = valuesOfNonBinaryUnicodeProperties.Script; // src/compiler/utilitiesPublic.ts function isExternalModuleNameRelative(moduleName) { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } function sortAndDeduplicateDiagnostics(diagnostics) { - return sortAndDeduplicate(diagnostics, compareDiagnostics); + return sortAndDeduplicate(diagnostics, compareDiagnostics, diagnosticsEqualityComparer); } function getDefaultLibFileName(options) { switch (getEmitScriptTarget(options)) { @@ -11391,8 +11372,7 @@ function getNonAssignedNameOfDeclaration(declaration) { return declaration.name; } function getNameOfDeclaration(declaration) { - if (declaration === void 0) - return void 0; + if (declaration === void 0) return void 0; return getNonAssignedNameOfDeclaration(declaration) || (isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : void 0); } function getAssignedName(node) { @@ -11576,8 +11556,7 @@ function getJSDocReturnType(node) { } function getJSDocTagsWorker(node, noCache) { var _a; - if (!canHaveJSDoc(node)) - return emptyArray; + if (!canHaveJSDoc(node)) return emptyArray; let tags = (_a = node.jsDoc) == null ? void 0 : _a.jsDocCache; if (tags === void 0 || noCache) { const comments = getJSDocCommentsAndTags(node, noCache); @@ -11609,7 +11588,7 @@ function getTextOfJSDocComment(comment) { function formatJSDocLink(link) { const kind = link.kind === 324 /* JSDocLink */ ? "link" : link.kind === 325 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; const name = link.name ? entityNameToString(link.name) : ""; - const space = link.name && link.text.startsWith("://") ? "" : " "; + const space = link.name && (link.text === "" || link.text.startsWith("://")) ? "" : " "; return `{@${kind} ${name}${space}${link.text}}`; } function getEffectiveTypeParameterDeclarations(node) { @@ -11995,6 +11974,10 @@ function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) { const kind = node.kind; return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */ || kind === 205 /* ImportType */; } +function isPropertyAccessOrQualifiedName(node) { + const kind = node.kind; + return kind === 211 /* PropertyAccessExpression */ || kind === 166 /* QualifiedName */; +} function isCallLikeOrFunctionLikeExpression(node) { return isCallLikeExpression(node) || isFunctionExpressionOrArrowFunction(node); } @@ -12265,7 +12248,7 @@ function canHaveLocals(node) { } } function isDeclarationKind(kind) { - return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 346 /* JSDocTypedefTag */ || kind === 338 /* JSDocCallbackTag */ || kind === 348 /* JSDocPropertyTag */; + return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 346 /* JSDocTypedefTag */ || kind === 338 /* JSDocCallbackTag */ || kind === 348 /* JSDocPropertyTag */ || kind === 202 /* NamedTupleMember */; } function isDeclarationStatementKind(kind) { return kind === 262 /* FunctionDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 270 /* NamespaceExportDeclaration */; @@ -12290,8 +12273,7 @@ function isStatement(node) { return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || isBlockStatement(node); } function isBlockStatement(node) { - if (node.kind !== 241 /* Block */) - return false; + if (node.kind !== 241 /* Block */) return false; if (node.parent !== void 0) { if (node.parent.kind === 258 /* TryStatement */ || node.parent.kind === 299 /* CatchClause */) { return false; @@ -12344,8 +12326,7 @@ function isGetAccessor(node) { return node.kind === 177 /* GetAccessor */; } function hasJSDocNodes(node) { - if (!canHaveJSDoc(node)) - return false; + if (!canHaveJSDoc(node)) return false; const { jsDoc } = node; return !!jsDoc && jsDoc.length > 0; } @@ -12599,8 +12580,7 @@ function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, pack moduleReference, mangleScopedPackageName(packageName) ); - if (result) - result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); + if (result) result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); return result; } function packageIdIsEqual(a, b) { @@ -12694,8 +12674,7 @@ function nodeIsPresent(node) { return !nodeIsMissing(node); } function insertStatementsAfterPrologue(to, from, isPrologueDirective2) { - if (from === void 0 || from.length === 0) - return to; + if (from === void 0 || from.length === 0) return to; let statementIndex = 0; for (; statementIndex < to.length; ++statementIndex) { if (!isPrologueDirective2(to[statementIndex])) { @@ -12706,8 +12685,7 @@ function insertStatementsAfterPrologue(to, from, isPrologueDirective2) { return to; } function insertStatementAfterPrologue(to, statement, isPrologueDirective2) { - if (statement === void 0) - return to; + if (statement === void 0) return to; let statementIndex = 0; for (; statementIndex < to.length; ++statementIndex) { if (!isPrologueDirective2(to[statementIndex])) { @@ -13458,8 +13436,7 @@ function tryGetTextOfPropertyName(name) { case 15 /* NoSubstitutionTemplateLiteral */: return escapeLeadingUnderscores(name.text); case 167 /* ComputedPropertyName */: - if (isStringOrNumericLiteralLike(name.expression)) - return escapeLeadingUnderscores(name.expression.text); + if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; case 295 /* JsxNamespacedName */: return getEscapedTextOfJsxNamespacedName(name); @@ -13486,7 +13463,7 @@ function entityNameToString(name) { return Debug.assertNever(name.name); } case 311 /* JSDocMemberName */: - return entityNameToString(name.left) + entityNameToString(name.right); + return entityNameToString(name.left) + "#" + entityNameToString(name.right); case 295 /* JsxNamespacedName */: return entityNameToString(name.namespace) + ":" + entityNameToString(name.name); default: @@ -13528,7 +13505,8 @@ function createFileDiagnosticFromMessageChain(file, start, length2, messageChain code: messageChain.code, category: messageChain.category, messageText: messageChain.next ? messageChain : messageChain.messageText, - relatedInformation + relatedInformation, + canonicalHead: messageChain.canonicalHead }; } function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) { @@ -13560,6 +13538,12 @@ function createDiagnosticForRange(sourceFile, range, message) { messageText: message.message }; } +function getCanonicalDiagnostic(message, ...args) { + return { + code: message.code, + messageText: formatMessage(message, ...args) + }; +} function getSpanOfTokenAtPosition(sourceFile, pos) { const scanner = createScanner( sourceFile.languageVersion, @@ -13655,6 +13639,26 @@ function getErrorSpanForNode(sourceFile, node) { const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); return getSpanOfTokenAtPosition(sourceFile, pos2); } + case 176 /* Constructor */: { + const constructorDeclaration = node; + const start = skipTrivia(sourceFile.text, constructorDeclaration.pos); + const scanner = createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + true, + sourceFile.languageVariant, + sourceFile.text, + /*onError*/ + void 0, + start + ); + let token = scanner.scan(); + while (token !== 137 /* ConstructorKeyword */ && token !== 1 /* EndOfFileToken */) { + token = scanner.scan(); + } + const end = scanner.getTokenEnd(); + return createTextSpanFromBounds(start, end); + } } if (errorNode === void 0) { return getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -13734,7 +13738,8 @@ function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { } function getJSDocCommentRanges(node, text) { const commentRanges = node.kind === 169 /* Parameter */ || node.kind === 168 /* TypeParameter */ || node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */ || node.kind === 217 /* ParenthesizedExpression */ || node.kind === 260 /* VariableDeclaration */ || node.kind === 281 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); - return filter(commentRanges, (comment) => text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); + return filter(commentRanges, (comment) => comment.end <= node.end && // Due to parse errors sometime empty parameter may get comments assigned to it that end up not in parameter range + text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); } var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; @@ -13920,13 +13925,11 @@ function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 261 /* VariableDeclarationList */ && node.parent.parent.kind === 243 /* VariableStatement */; } function isCommonJsExportedExpression(node) { - if (!isInJSFile(node)) - return false; + if (!isInJSFile(node)) return false; return isObjectLiteralExpression(node.parent) && isBinaryExpression(node.parent.parent) && getAssignmentDeclarationKind(node.parent.parent) === 2 /* ModuleExports */ || isCommonJsExportPropertyAssignment(node.parent); } function isCommonJsExportPropertyAssignment(node) { - if (!isInJSFile(node)) - return false; + if (!isInJSFile(node)) return false; return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 1 /* ExportsProperty */; } function isValidESSymbolDeclaration(node) { @@ -13973,8 +13976,7 @@ function isThisTypePredicate(predicate) { } function forEachPropertyAssignment(objectLiteral, key, callback, key2) { return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, (property) => { - if (!isPropertyAssignment(property)) - return void 0; + if (!isPropertyAssignment(property)) return void 0; const propName = tryGetTextOfPropertyName(property.name); return key === propName || key2 && key2 === propName ? callback(property) : void 0; }); @@ -14216,8 +14218,7 @@ function nodeCanBeDecorated(useLegacyDecorators, node, parent, grandparent) { case 174 /* MethodDeclaration */: return node.body !== void 0 && parent !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent) : isClassLike(parent)); case 169 /* Parameter */: - if (!useLegacyDecorators) - return false; + if (!useLegacyDecorators) return false; return parent !== void 0 && parent.body !== void 0 && (parent.kind === 176 /* Constructor */ || parent.kind === 174 /* MethodDeclaration */ || parent.kind === 178 /* SetAccessor */) && getThisParameter(parent) !== node && grandparent !== void 0 && grandparent.kind === 263 /* ClassDeclaration */; } return false; @@ -14243,8 +14244,7 @@ function childIsDecorated(useLegacyDecorators, node, parent) { } } function classOrConstructorParameterIsDecorated(useLegacyDecorators, node) { - if (nodeIsDecorated(useLegacyDecorators, node)) - return true; + if (nodeIsDecorated(useLegacyDecorators, node)) return true; const constructor = getFirstConstructorWithBody(node); return !!constructor && childIsDecorated(useLegacyDecorators, constructor, node); } @@ -14265,10 +14265,8 @@ function classElementOrClassElementParameterIsDecorated(useLegacyDecorators, nod } if (parameters) { for (const parameter of parameters) { - if (parameterIsThisKeyword(parameter)) - continue; - if (nodeIsDecorated(useLegacyDecorators, parameter, node, parent)) - return true; + if (parameterIsThisKeyword(parameter)) continue; + if (nodeIsDecorated(useLegacyDecorators, parameter, node, parent)) return true; } } return false; @@ -15189,8 +15187,7 @@ function walkUpParenthesizedTypesAndGetParentAndChild(node) { return [child, node]; } function skipTypeParentheses(node) { - while (isParenthesizedTypeNode(node)) - node = node.type; + while (isParenthesizedTypeNode(node)) node = node.type; return node; } function skipParentheses(node, excludeJSDocTypeAssertions) { @@ -15206,8 +15203,7 @@ function isDeleteTarget(node) { } function isNodeDescendantOf(node, ancestor) { while (node) { - if (node === ancestor) - return true; + if (node === ancestor) return true; node = node.parent; } return false; @@ -15494,8 +15490,7 @@ function isNamedEvaluationSource(node) { return false; } function isNamedEvaluation(node, cb) { - if (!isNamedEvaluationSource(node)) - return false; + if (!isNamedEvaluationSource(node)) return false; switch (node.kind) { case 303 /* PropertyAssignment */: return isAnonymousFunctionDefinition(node.initializer, cb); @@ -15752,6 +15747,9 @@ function createDiagnosticCollection() { if (result >= 0) { return diagnostics[result]; } + if (~result > 0 && diagnosticsEqualityComparer(diagnostic, diagnostics[~result - 1])) { + return diagnostics[~result - 1]; + } return void 0; } function add(diagnostic) { @@ -15770,7 +15768,7 @@ function createDiagnosticCollection() { } diagnostics = nonFileDiagnostics; } - insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation); + insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation, diagnosticsEqualityComparer); } function getGlobalDiagnostics() { hasReadNonFileDiagnostics = true; @@ -15918,13 +15916,11 @@ function createTextWriter(newLine) { } } function write(s) { - if (s) - hasTrailingComment = false; + if (s) hasTrailingComment = false; writeText(s); } function writeComment(s) { - if (s) - hasTrailingComment = true; + if (s) hasTrailingComment = true; writeText(s); } function reset() { @@ -16124,8 +16120,7 @@ function getPossibleOriginalInputExtensionForExtension(path) { } function getPathsBasePath(options, host) { var _a; - if (!options.paths) - return void 0; + if (!options.paths) return void 0; return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { @@ -16147,29 +16142,19 @@ function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { } function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) { const options = host.getCompilerOptions(); - if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) - return false; - if (sourceFile.isDeclarationFile) - return false; - if (host.isSourceFileFromExternalLibrary(sourceFile)) - return false; - if (forceDtsEmit) - return true; - if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) - return false; - if (!isJsonSourceFile(sourceFile)) - return true; - if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) - return false; - if (options.outFile) - return true; - if (!options.outDir) - return false; + if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) return false; + if (sourceFile.isDeclarationFile) return false; + if (host.isSourceFileFromExternalLibrary(sourceFile)) return false; + if (forceDtsEmit) return true; + if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) return false; + if (!isJsonSourceFile(sourceFile)) return true; + if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) return false; + if (options.outFile) return true; + if (!options.outDir) return false; if (options.rootDir || options.composite && options.configFilePath) { const commonDir = getNormalizedAbsolutePath(getCommonSourceDirectory(options, () => [], host.getCurrentDirectory(), host.getCanonicalFileName), host.getCurrentDirectory()); const outputPath = getSourceFilePathInNewDirWorker(sourceFile.fileName, options.outDir, host.getCurrentDirectory(), commonDir, host.getCanonicalFileName); - if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) - return false; + if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) return false; } return true; } @@ -16300,11 +16285,10 @@ function getAllAccessorDeclarations(declarations, accessor) { }; } function getEffectiveTypeAnnotationNode(node) { - if (!isInJSFile(node) && isFunctionDeclaration(node)) - return void 0; + if (!isInJSFile(node) && isFunctionDeclaration(node)) return void 0; + if (isTypeAliasDeclaration(node)) return void 0; const type = node.type; - if (type || !isInJSFile(node)) - return type; + if (type || !isInJSFile(node)) return type; return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); } function getEffectiveReturnTypeNode(node) { @@ -16536,19 +16520,13 @@ function getRawJSDocModifierFlagsNoCache(node) { let flags = 0 /* None */; if (!!node.parent && !isParameter(node)) { if (isInJSFile(node)) { - if (getJSDocPublicTagNoCache(node)) - flags |= 8388608 /* JSDocPublic */; - if (getJSDocPrivateTagNoCache(node)) - flags |= 16777216 /* JSDocPrivate */; - if (getJSDocProtectedTagNoCache(node)) - flags |= 33554432 /* JSDocProtected */; - if (getJSDocReadonlyTagNoCache(node)) - flags |= 67108864 /* JSDocReadonly */; - if (getJSDocOverrideTagNoCache(node)) - flags |= 134217728 /* JSDocOverride */; - } - if (getJSDocDeprecatedTagNoCache(node)) - flags |= 65536 /* Deprecated */; + if (getJSDocPublicTagNoCache(node)) flags |= 8388608 /* JSDocPublic */; + if (getJSDocPrivateTagNoCache(node)) flags |= 16777216 /* JSDocPrivate */; + if (getJSDocProtectedTagNoCache(node)) flags |= 33554432 /* JSDocProtected */; + if (getJSDocReadonlyTagNoCache(node)) flags |= 67108864 /* JSDocReadonly */; + if (getJSDocOverrideTagNoCache(node)) flags |= 134217728 /* JSDocOverride */; + } + if (getJSDocDeprecatedTagNoCache(node)) flags |= 65536 /* Deprecated */; } return flags; } @@ -16741,11 +16719,9 @@ function isEmptyArrayLiteral(expression) { return expression.kind === 209 /* ArrayLiteralExpression */ && expression.elements.length === 0; } function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol) || !symbol.declarations) - return void 0; + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return void 0; for (const decl of symbol.declarations) { - if (decl.localSymbol) - return decl.localSymbol; + if (decl.localSymbol) return decl.localSymbol; } return void 0; } @@ -16810,8 +16786,7 @@ function base64encode(host, input) { } function readJsonOrUndefined(path, hostOrText) { const jsonText = isString(hostOrText) ? hostOrText : hostOrText.readFile(path); - if (!jsonText) - return void 0; + if (!jsonText) return void 0; const result = parseConfigFileTextToJson(path, jsonText); return !result.error ? result.config : void 0; } @@ -16989,6 +16964,9 @@ function getDeclarationModifierFlagsFromSymbol(s, isWrite = false) { } return 0; } +function skipAlias(symbol, checker) { + return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol; +} function getCombinedLocalAndExportSymbolFlags(symbol) { return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } @@ -17091,8 +17069,7 @@ function isUMDExportSymbol(symbol) { function getLastChild(node) { let lastChild; forEachChild(node, (child) => { - if (nodeIsPresent(child)) - lastChild = child; + if (nodeIsPresent(child)) lastChild = child; }, (children) => { for (let i = children.length - 1; i >= 0; i--) { if (nodeIsPresent(children[i])) { @@ -17369,61 +17346,125 @@ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } function compareDiagnosticsSkipRelatedInformation(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareMessageText(d1.messageText, d2.messageText) || 0 /* EqualTo */; + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(code1, code2) || compareMessageText(d1, d2) || 0 /* EqualTo */; } function compareRelatedInformation(d1, d2) { if (!d1.relatedInformation && !d2.relatedInformation) { return 0 /* EqualTo */; } if (d1.relatedInformation && d2.relatedInformation) { - return compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || forEach(d1.relatedInformation, (d1i, index) => { + return compareValues(d2.relatedInformation.length, d1.relatedInformation.length) || forEach(d1.relatedInformation, (d1i, index) => { const d2i = d2.relatedInformation[index]; return compareDiagnostics(d1i, d2i); }) || 0 /* EqualTo */; } return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; } -function compareMessageText(t1, t2) { - if (typeof t1 === "string" && typeof t2 === "string") { - return compareStringsCaseSensitive(t1, t2); - } else if (typeof t1 === "string") { - return -1 /* LessThan */; - } else if (typeof t2 === "string") { - return 1 /* GreaterThan */; +function compareMessageText(d1, d2) { + let headMsg1 = getDiagnosticMessage(d1); + let headMsg2 = getDiagnosticMessage(d2); + if (typeof headMsg1 !== "string") { + headMsg1 = headMsg1.messageText; + } + if (typeof headMsg2 !== "string") { + headMsg2 = headMsg2.messageText; + } + const chain1 = typeof d1.messageText !== "string" ? d1.messageText.next : void 0; + const chain2 = typeof d2.messageText !== "string" ? d2.messageText.next : void 0; + let res = compareStringsCaseSensitive(headMsg1, headMsg2); + if (res) { + return res; } - let res = compareStringsCaseSensitive(t1.messageText, t2.messageText); + res = compareMessageChain(chain1, chain2); if (res) { return res; } - if (!t1.next && !t2.next) { + if (d1.canonicalHead && !d2.canonicalHead) { + return -1 /* LessThan */; + } + if (d2.canonicalHead && !d1.canonicalHead) { + return 1 /* GreaterThan */; + } + return 0 /* EqualTo */; +} +function compareMessageChain(c1, c2) { + if (c1 === void 0 && c2 === void 0) { return 0 /* EqualTo */; } - if (!t1.next) { + if (c1 === void 0) { + return 1 /* GreaterThan */; + } + if (c2 === void 0) { return -1 /* LessThan */; } - if (!t2.next) { + return compareMessageChainSize(c1, c2) || compareMessageChainContent(c1, c2); +} +function compareMessageChainSize(c1, c2) { + if (c1 === void 0 && c2 === void 0) { + return 0 /* EqualTo */; + } + if (c1 === void 0) { return 1 /* GreaterThan */; } - const len = Math.min(t1.next.length, t2.next.length); - for (let i = 0; i < len; i++) { - res = compareMessageText(t1.next[i], t2.next[i]); + if (c2 === void 0) { + return -1 /* LessThan */; + } + let res = compareValues(c2.length, c1.length); + if (res) { + return res; + } + for (let i = 0; i < c2.length; i++) { + res = compareMessageChainSize(c1[i].next, c2[i].next); if (res) { return res; } } - if (t1.next.length < t2.next.length) { - return -1 /* LessThan */; - } else if (t1.next.length > t2.next.length) { - return 1 /* GreaterThan */; + return 0 /* EqualTo */; +} +function compareMessageChainContent(c1, c2) { + let res; + for (let i = 0; i < c2.length; i++) { + res = compareStringsCaseSensitive(c1[i].messageText, c2[i].messageText); + if (res) { + return res; + } + if (c1[i].next === void 0) { + continue; + } + res = compareMessageChainContent(c1[i].next, c2[i].next); + if (res) { + return res; + } } return 0 /* EqualTo */; } +function diagnosticsEqualityComparer(d1, d2) { + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + const msg1 = getDiagnosticMessage(d1); + const msg2 = getDiagnosticMessage(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) === 0 /* EqualTo */ && compareValues(d1.start, d2.start) === 0 /* EqualTo */ && compareValues(d1.length, d2.length) === 0 /* EqualTo */ && compareValues(code1, code2) === 0 /* EqualTo */ && messageTextEqualityComparer(msg1, msg2); +} +function getDiagnosticCode(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.code) || d.code; +} +function getDiagnosticMessage(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.messageText) || d.messageText; +} +function messageTextEqualityComparer(m1, m2) { + const t1 = typeof m1 === "string" ? m1 : m1.messageText; + const t2 = typeof m2 === "string" ? m2 : m2.messageText; + return compareStringsCaseSensitive(t1, t2) === 0 /* EqualTo */; +} function getLanguageVariant(scriptKind) { return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; } function walkTreeForJSXTags(node) { - if (!(node.transformFlags & 2 /* ContainsJsx */)) - return void 0; + if (!(node.transformFlags & 2 /* ContainsJsx */)) return void 0; return isJsxOpeningLikeElement(node) || isJsxFragment(node) ? node : forEachChild(node, walkTreeForJSXTags); } function isFileModuleFromUsingJSXTag(file) { @@ -17788,8 +17829,7 @@ function createSymlinkCache(cwd, getCanonicalFileName) { return !!(symlinkedFiles == null ? void 0 : symlinkedFiles.size) || !!symlinkedDirectories && !!forEachEntry(symlinkedDirectories, (value) => !!value); } function processResolution(cache, resolution) { - if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) - return; + if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) return; const { resolvedFileName, originalPath } = resolution; cache.setSymlinkedFile(toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName); const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || emptyArray; @@ -17962,17 +18002,14 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa return flatten(results); function visitDirectory(path2, absolutePath, depth2) { const canonicalPath = toCanonical(realpath(absolutePath)); - if (visited.has(canonicalPath)) - return; + if (visited.has(canonicalPath)) return; visited.set(canonicalPath, true); const { files, directories } = getFileSystemEntries(path2); for (const current of sort(files, compareStringsCaseSensitive)) { const name = combinePaths(path2, current); const absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name, extensions)) - continue; - if (excludeRegex && excludeRegex.test(absoluteName)) - continue; + if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; + if (excludeRegex && excludeRegex.test(absoluteName)) continue; if (!includeFileRegexes) { results[0].push(name); } else { @@ -18070,12 +18107,9 @@ function getSupportedExtensions(options, extraFileExtensions) { return extensions; } function getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { - if (!options || !getResolveJsonModule(options)) - return supportedExtensions; - if (supportedExtensions === allSupportedExtensions) - return allSupportedExtensionsWithJson; - if (supportedExtensions === supportedTSExtensions) - return supportedTSExtensionsWithJson; + if (!options || !getResolveJsonModule(options)) return supportedExtensions; + if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson; + if (supportedExtensions === supportedTSExtensions) return supportedTSExtensionsWithJson; return [...supportedExtensions, [".json" /* Json */]]; } function isJSLike(scriptKind) { @@ -18153,8 +18187,7 @@ function getRequiresAtTopOfFile(sourceFile) { return requires || emptyArray; } function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { - if (!fileName) - return false; + if (!fileName) return false; const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); for (const extension of flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions))) { if (fileExtensionIs(fileName, extension)) { @@ -18285,7 +18318,15 @@ function rangeOfTypeParameters(sourceFile, typeParameters) { return { pos, end }; } function skipTypeChecking(sourceFile, options, host) { - return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName); + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || options.noCheck || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) || !canIncludeBindAndCheckDiagnsotics(sourceFile, options); +} +function canIncludeBindAndCheckDiagnsotics(sourceFile, options) { + if (!!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false) return false; + if (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */) return true; + const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); + const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); + return isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; } function isJsonEqual(a, b) { return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && equalOwnProperties(a, b, isJsonEqual); @@ -18323,8 +18364,7 @@ function parsePseudoBigInt(stringValue) { const shiftedDigit = digit << (bitOffset & 15); segments[segment] |= shiftedDigit; const residual = shiftedDigit >>> 16; - if (residual) - segments[segment + 1] |= residual; + if (residual) segments[segment + 1] |= residual; } let base10Value = ""; let firstNonzeroSegment = segments.length - 1; @@ -18355,8 +18395,7 @@ function parseValidBigInt(text) { return { negative, base10Value }; } function isValidBigIntString(s, roundTripOnly) { - if (s === "") - return false; + if (s === "") return false; const scanner = createScanner( 99 /* ESNext */, /*skipTrivia*/ @@ -18393,8 +18432,7 @@ function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */; } function isIdentifierInNonEmittingHeritageClause(node) { - if (node.kind !== 80 /* Identifier */) - return false; + if (node.kind !== 80 /* Identifier */) return false; const heritageClause = findAncestor(node.parent, (parent) => { switch (parent.kind) { case 298 /* HeritageClause */: @@ -18412,13 +18450,11 @@ function isIdentifierTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName); } function arrayIsHomogeneous(array, comparer = equateValues) { - if (array.length < 2) - return true; + if (array.length < 2) return true; const first2 = array[0]; for (let i = 1, length2 = array.length; i < length2; i++) { const target = array[i]; - if (!comparer(first2, target)) - return false; + if (!comparer(first2, target)) return false; } return true; } @@ -18449,8 +18485,7 @@ function setParent(child, parent) { return child; } function setParentRecursive(rootNode, incremental) { - if (!rootNode) - return rootNode; + if (!rootNode) return rootNode; forEachChildRecursively(rootNode, isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild); return rootNode; function bindParentToChildIgnoringJSDoc(child, parent) { @@ -18489,14 +18524,12 @@ function expressionResultIsUnused(node) { return true; } if (isCommaListExpression(parent)) { - if (node !== last(parent.elements)) - return true; + if (node !== last(parent.elements)) return true; node = parent; continue; } if (isBinaryExpression(parent) && parent.operatorToken.kind === 28 /* CommaToken */) { - if (node === parent.left) - return true; + if (node === parent.left) return true; node = parent; continue; } @@ -18507,8 +18540,7 @@ function containsIgnoredPath(path) { return some(ignoredPaths, (p) => path.includes(p)); } function getContainingNodeArray(node) { - if (!node.parent) - return void 0; + if (!node.parent) return void 0; switch (node.kind) { case 168 /* TypeParameter */: const { parent: parent2 } = node; @@ -18947,13 +18979,15 @@ function createNameResolver({ let useResult = true; if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 320 /* JSDoc */) { - useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; + useResult = result.flags & 262144 /* TypeParameter */ ? !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so type parameters are accessible from them + lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; } if (meaning & result.flags & 3 /* Variable */) { if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { - useResult = lastLocation.kind === 169 /* Parameter */ || lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); + useResult = lastLocation.kind === 169 /* Parameter */ || !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so parameters are accessible from them + lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); } } } else if (location.kind === 194 /* ConditionalType */) { @@ -18969,8 +19003,7 @@ function createNameResolver({ withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { case 307 /* SourceFile */: - if (!isExternalOrCommonJsModule(location)) - break; + if (!isExternalOrCommonJsModule(location)) break; case 267 /* ModuleDeclaration */: const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; if (location.kind === 307 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { @@ -19222,8 +19255,7 @@ function createNameResolver({ if (isBindingElement(node) && node.dotDotDotToken && isObjectBindingPattern(node.parent)) { return target < 4 /* ES2017 */; } - if (isTypeNode(node)) - return false; + if (isTypeNode(node)) return false; return forEachChild(node, requiresScopeChangeWorker) || false; } } @@ -19685,30 +19717,21 @@ function createParenthesizerRules(factory2) { return factory2.createNodeArray(sameMap(types, parenthesizeElementTypeOfTupleType)); } function parenthesizeElementTypeOfTupleType(type) { - if (hasJSDocPostfixQuestion(type)) - return factory2.createParenthesizedType(type); + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); return type; } function hasJSDocPostfixQuestion(type) { - if (isJSDocNullableType(type)) - return type.postfix; - if (isNamedTupleMember(type)) - return hasJSDocPostfixQuestion(type.type); - if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) - return hasJSDocPostfixQuestion(type.type); - if (isConditionalTypeNode(type)) - return hasJSDocPostfixQuestion(type.falseType); - if (isUnionTypeNode(type)) - return hasJSDocPostfixQuestion(last(type.types)); - if (isIntersectionTypeNode(type)) - return hasJSDocPostfixQuestion(last(type.types)); - if (isInferTypeNode(type)) - return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); + if (isJSDocNullableType(type)) return type.postfix; + if (isNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.type); + if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.type); + if (isConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.falseType); + if (isUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isInferTypeNode(type)) return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); return false; } function parenthesizeTypeOfOptionalType(type) { - if (hasJSDocPostfixQuestion(type)) - return factory2.createParenthesizedType(type); + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); return parenthesizeNonArrayTypeOfPostfixType(type); } function parenthesizeLeadingTypeArgument(node) { @@ -19770,8 +19793,7 @@ function createNodeConverters(factory2) { convertToAssignmentElementTarget }; function convertToFunctionBlock(node, multiLine) { - if (isBlock(node)) - return node; + if (isBlock(node)) return node; const returnStatement = factory2.createReturnStatement(node); setTextRange(returnStatement, node); const body = factory2.createBlock([returnStatement], multiLine); @@ -19780,8 +19802,7 @@ function createNodeConverters(factory2) { } function convertToFunctionExpression(node) { var _a; - if (!node.body) - return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); + if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); const updated = factory2.createFunctionExpression( (_a = getModifiers(node)) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)), node.asteriskToken, @@ -20619,8 +20640,7 @@ function createNodeFactory(flags, baseFactory2) { const node = createBaseDeclaration(9 /* NumericLiteral */); node.text = text; node.numericLiteralFlags = numericLiteralFlags; - if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 1024 /* ContainsES2015 */; + if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) node.transformFlags |= 1024 /* ContainsES2015 */; return node; } function createBigIntLiteral(value) { @@ -20638,8 +20658,7 @@ function createNodeFactory(flags, baseFactory2) { function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) { const node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - if (hasExtendedUnicodeEscape) - node.transformFlags |= 1024 /* ContainsES2015 */; + if (hasExtendedUnicodeEscape) node.transformFlags |= 1024 /* ContainsES2015 */; return node; } function createStringLiteralFromNode(sourceNode) { @@ -20724,8 +20743,7 @@ function createNodeFactory(flags, baseFactory2) { originalKeywordKind = void 0; } const node = createBaseIdentifier(escapeLeadingUnderscores(text)); - if (hasExtendedUnicodeEscape) - node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */; + if (hasExtendedUnicodeEscape) node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */; if (node.escapedText === "await") { node.transformFlags |= 67108864 /* ContainsPossibleTopLevelAwait */; } @@ -20736,8 +20754,7 @@ function createNodeFactory(flags, baseFactory2) { } function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) { let flags2 = 1 /* Auto */; - if (reservedInNestedScopes) - flags2 |= 8 /* ReservedInNestedScopes */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; const name = createBaseGeneratedIdentifier("", flags2, prefix, suffix); if (recordTempVariable) { recordTempVariable(name); @@ -20746,8 +20763,7 @@ function createNodeFactory(flags, baseFactory2) { } function createLoopVariable(reservedInNestedScopes) { let flags2 = 2 /* Loop */; - if (reservedInNestedScopes) - flags2 |= 8 /* ReservedInNestedScopes */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; return createBaseGeneratedIdentifier( "", flags2, @@ -20772,8 +20788,7 @@ function createNodeFactory(flags, baseFactory2) { suffix, idText ) : `generated@${getNodeId(node)}`; - if (prefix || suffix) - flags2 |= 16 /* Optimistic */; + if (prefix || suffix) flags2 |= 16 /* Optimistic */; const name = createBaseGeneratedIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); name.original = node; return name; @@ -20785,8 +20800,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createPrivateIdentifier(text) { - if (!startsWith(text, "#")) - Debug.fail("First character of private identifier must be #: " + text); + if (!startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); return createBasePrivateIdentifier(escapeLeadingUnderscores(text)); } function createBaseGeneratedPrivateIdentifier(text, autoGenerateFlags, prefix, suffix) { @@ -20801,8 +20815,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createUniquePrivateName(text, prefix, suffix) { - if (text && !startsWith(text, "#")) - Debug.fail("First character of private identifier must be #: " + text); + if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); const autoGenerateFlags = 8 /* ReservedInNestedScopes */ | (text ? 3 /* Unique */ : 1 /* Auto */); return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix); } @@ -20900,36 +20913,21 @@ function createNodeFactory(flags, baseFactory2) { } function createModifiersFromModifierFlags(flags2) { const result = []; - if (flags2 & 32 /* Export */) - result.push(createModifier(95 /* ExportKeyword */)); - if (flags2 & 128 /* Ambient */) - result.push(createModifier(138 /* DeclareKeyword */)); - if (flags2 & 2048 /* Default */) - result.push(createModifier(90 /* DefaultKeyword */)); - if (flags2 & 4096 /* Const */) - result.push(createModifier(87 /* ConstKeyword */)); - if (flags2 & 1 /* Public */) - result.push(createModifier(125 /* PublicKeyword */)); - if (flags2 & 2 /* Private */) - result.push(createModifier(123 /* PrivateKeyword */)); - if (flags2 & 4 /* Protected */) - result.push(createModifier(124 /* ProtectedKeyword */)); - if (flags2 & 64 /* Abstract */) - result.push(createModifier(128 /* AbstractKeyword */)); - if (flags2 & 256 /* Static */) - result.push(createModifier(126 /* StaticKeyword */)); - if (flags2 & 16 /* Override */) - result.push(createModifier(164 /* OverrideKeyword */)); - if (flags2 & 8 /* Readonly */) - result.push(createModifier(148 /* ReadonlyKeyword */)); - if (flags2 & 512 /* Accessor */) - result.push(createModifier(129 /* AccessorKeyword */)); - if (flags2 & 1024 /* Async */) - result.push(createModifier(134 /* AsyncKeyword */)); - if (flags2 & 8192 /* In */) - result.push(createModifier(103 /* InKeyword */)); - if (flags2 & 16384 /* Out */) - result.push(createModifier(147 /* OutKeyword */)); + if (flags2 & 32 /* Export */) result.push(createModifier(95 /* ExportKeyword */)); + if (flags2 & 128 /* Ambient */) result.push(createModifier(138 /* DeclareKeyword */)); + if (flags2 & 2048 /* Default */) result.push(createModifier(90 /* DefaultKeyword */)); + if (flags2 & 4096 /* Const */) result.push(createModifier(87 /* ConstKeyword */)); + if (flags2 & 1 /* Public */) result.push(createModifier(125 /* PublicKeyword */)); + if (flags2 & 2 /* Private */) result.push(createModifier(123 /* PrivateKeyword */)); + if (flags2 & 4 /* Protected */) result.push(createModifier(124 /* ProtectedKeyword */)); + if (flags2 & 64 /* Abstract */) result.push(createModifier(128 /* AbstractKeyword */)); + if (flags2 & 256 /* Static */) result.push(createModifier(126 /* StaticKeyword */)); + if (flags2 & 16 /* Override */) result.push(createModifier(164 /* OverrideKeyword */)); + if (flags2 & 8 /* Readonly */) result.push(createModifier(148 /* ReadonlyKeyword */)); + if (flags2 & 512 /* Accessor */) result.push(createModifier(129 /* AccessorKeyword */)); + if (flags2 & 1024 /* Async */) result.push(createModifier(134 /* AsyncKeyword */)); + if (flags2 & 8192 /* In */) result.push(createModifier(103 /* InKeyword */)); + if (flags2 & 16384 /* Out */) result.push(createModifier(147 /* OutKeyword */)); return result.length ? result : void 0; } function createQualifiedName(left, right) { @@ -22286,8 +22284,7 @@ function createNodeFactory(flags, baseFactory2) { node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | 1024 /* ContainsES2015 */; - if (awaitModifier) - node.transformFlags |= 128 /* ContainsES2018 */; + if (awaitModifier) node.transformFlags |= 128 /* ContainsES2018 */; node.jsDoc = void 0; node.locals = void 0; node.nextContainer = void 0; @@ -23523,8 +23520,7 @@ function createNodeFactory(flags, baseFactory2) { clone.transformFlags = node.transformFlags; setOriginal(clone, node); const typeArguments = getIdentifierTypeArguments(node); - if (typeArguments) - setIdentifierTypeArguments(clone, typeArguments); + if (typeArguments) setIdentifierTypeArguments(clone, typeArguments); return clone; } function cloneGeneratedPrivateIdentifier(node) { @@ -23897,12 +23893,9 @@ function createNodeFactory(flags, baseFactory2) { if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); - if (!allowSourceMaps) - emitFlags |= 96 /* NoSourceMap */; - if (!allowComments) - emitFlags |= 3072 /* NoComments */; - if (emitFlags) - setEmitFlags(name, emitFlags); + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(name, emitFlags); return name; } return getGeneratedNameForNode(node); @@ -23923,12 +23916,9 @@ function createNodeFactory(flags, baseFactory2) { const qualifiedName = createPropertyAccessExpression(ns, nodeIsSynthesized(name) ? name : cloneNode(name)); setTextRange(qualifiedName, name); let emitFlags = 0; - if (!allowSourceMaps) - emitFlags |= 96 /* NoSourceMap */; - if (!allowComments) - emitFlags |= 3072 /* NoComments */; - if (emitFlags) - setEmitFlags(qualifiedName, emitFlags); + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(qualifiedName, emitFlags); return qualifiedName; } function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { @@ -24221,8 +24211,7 @@ function propagatePropertyNameFlagsOfChild(node, transformFlags) { return transformFlags | node.transformFlags & 134234112 /* PropertyNamePropagatingFlags */; } function propagateChildFlags(child) { - if (!child) - return 0 /* None */; + if (!child) return 0 /* None */; const childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind); return isNamedDeclaration(child) && isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags; } @@ -24324,8 +24313,7 @@ function setOriginalNode(node, original) { node.original = original; if (original) { const emitNode = original.emitNode; - if (emitNode) - node.emitNode = mergeEmitNode(emitNode, node.emitNode); + if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); } } return node; @@ -24346,8 +24334,7 @@ function mergeEmitNode(sourceEmitNode, destEmitNode) { classThis, assignedName } = sourceEmitNode; - if (!destEmitNode) - destEmitNode = {}; + if (!destEmitNode) destEmitNode = {}; if (flags) { destEmitNode.flags = flags; } @@ -24392,8 +24379,7 @@ function mergeEmitNode(sourceEmitNode, destEmitNode) { return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { - if (!destRanges) - destRanges = []; + if (!destRanges) destRanges = []; for (const key in sourceRanges) { destRanges[key] = sourceRanges[key]; } @@ -24540,8 +24526,7 @@ function getEmitHelpers(node) { function moveEmitHelpers(source, target, predicate) { const sourceEmitNode = source.emitNode; const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; - if (!some(sourceEmitHelpers)) - return; + if (!some(sourceEmitHelpers)) return; const targetEmitNode = getOrCreateEmitNode(target); let helpersRemoved = 0; for (let i = 0; i < sourceEmitHelpers.length; i++) { @@ -24794,10 +24779,8 @@ function createEmitHelperFactory(context) { function createESDecorateClassElementAccessObject(name, access) { const properties = []; properties.push(createESDecorateClassElementAccessHasMethod(name)); - if (access.get) - properties.push(createESDecorateClassElementAccessGetMethod(name)); - if (access.set) - properties.push(createESDecorateClassElementAccessSetMethod(name)); + if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name)); + if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name)); return factory2.createObjectLiteralExpression(properties); } function createESDecorateClassElementContextObject(contextIn) { @@ -25130,14 +25113,10 @@ function createEmitHelperFactory(context) { } } function compareEmitHelpers(x, y) { - if (x === y) - return 0 /* EqualTo */; - if (x.priority === y.priority) - return 0 /* EqualTo */; - if (x.priority === void 0) - return 1 /* GreaterThan */; - if (y.priority === void 0) - return -1 /* LessThan */; + if (x === y) return 0 /* EqualTo */; + if (x.priority === y.priority) return 0 /* EqualTo */; + if (x.priority === void 0) return 1 /* GreaterThan */; + if (y.priority === void 0) return -1 /* LessThan */; return compareValues(x.priority, y.priority); } function helperString(input, ...args) { @@ -25581,7 +25560,7 @@ var addDisposableResourceHelper = { var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose; + var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; @@ -25589,8 +25568,10 @@ var addDisposableResourceHelper = { if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; + if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { @@ -26242,8 +26223,7 @@ function isJSDocImportTag(node) { // src/compiler/factory/nodeChildren.ts var nodeChildren = /* @__PURE__ */ new WeakMap(); function getNodeChildren(node) { - if (!isNodeKind(node.kind)) - return emptyArray; + if (!isNodeKind(node.kind)) return emptyArray; return nodeChildren.get(node); } function setNodeChildren(node, children) { @@ -27071,14 +27051,11 @@ var BinaryExpressionState; function nextState(machine, currentState) { switch (currentState) { case enter: - if (machine.onLeft) - return left; + if (machine.onLeft) return left; case left: - if (machine.onOperator) - return operator; + if (machine.onOperator) return operator; case operator: - if (machine.onRight) - return right; + if (machine.onRight) return right; case right: return exit; case exit: @@ -27140,10 +27117,8 @@ function isExportOrDefaultModifier(node) { return isExportOrDefaultKeywordKind(kind); } function elideNodes(factory2, nodes) { - if (nodes === void 0) - return void 0; - if (nodes.length === 0) - return nodes; + if (nodes === void 0) return void 0; + if (nodes.length === 0) return nodes; return setTextRange(factory2.createNodeArray([], nodes.hasTrailingComma), nodes); } function getNodeForGeneratedName(name) { @@ -27300,8 +27275,7 @@ function flattenCommaList(node) { return expressions; } function containsObjectRestOrSpread(node) { - if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) - return true; + if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) return true; if (node.transformFlags & 128 /* ContainsES2018 */) { for (const element of getElementsOfBindingOrAssignmentPattern(node)) { const target = getTargetOfBindingOrAssignmentElement(element); @@ -27310,8 +27284,7 @@ function containsObjectRestOrSpread(node) { return true; } if (target.transformFlags & 128 /* ContainsES2018 */) { - if (containsObjectRestOrSpread(target)) - return true; + if (containsObjectRestOrSpread(target)) return true; } } } @@ -27883,8 +27856,7 @@ function forEachChildRecursively(rootNode, cbNode, cbNodes) { if (cbNodes) { const res = cbNodes(current, parent); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } } @@ -27895,8 +27867,7 @@ function forEachChildRecursively(rootNode, cbNode, cbNodes) { } else { const res = cbNode(current, parent); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } if (current.kind >= 166 /* FirstNode */) { @@ -28308,8 +28279,7 @@ var Parser; } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - if (jsDoc.length) - node.jsDoc = jsDoc; + if (jsDoc.length) node.jsDoc = jsDoc; if (hasDeprecatedTag) { hasDeprecatedTag = false; node.flags |= 536870912 /* Deprecated */; @@ -28413,8 +28383,7 @@ var Parser; if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */) { const oldSourceFile = sourceFile; sourceFile = reparseTopLevelAwait(sourceFile); - if (oldSourceFile !== sourceFile) - setFields(sourceFile); + if (oldSourceFile !== sourceFile) setFields(sourceFile); } return sourceFile; function setFields(sourceFile2) { @@ -28539,10 +28508,7 @@ var Parser; function parseErrorAtPosition(start, length2, message, ...args) { const lastError = lastOrUndefined(parseDiagnostics); let result; - if (message.category === 3 /* Message */ && lastError && start === lastError.start && length2 === lastError.length) { - result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); - addRelatedInfo(lastError, result); - } else if (!lastError || start !== lastError.start) { + if (!lastError || start !== lastError.start) { result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); parseDiagnostics.push(result); } @@ -28805,8 +28771,7 @@ var Parser; } function parseExpectedTokenJSDoc(t) { const optional = parseOptionalTokenJSDoc(t); - if (optional) - return optional; + if (optional) return optional; Debug.assert(isKeywordOrPunctuation(t)); return createMissingNode( t, @@ -30123,8 +30088,7 @@ var Parser; } else { const type = parseTypeAnnotation(); node = factory2.createPropertySignature(modifiers, name, questionToken, type); - if (token() === 64 /* EqualsToken */) - node.initializer = parseInitializer(); + if (token() === 64 /* EqualsToken */) node.initializer = parseInitializer(); } parseTypeMemberSemicolon(); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -31494,8 +31458,7 @@ var Parser; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { const child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken()); - if (!child) - break; + if (!child) break; list.push(child); if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { break; @@ -32522,8 +32485,7 @@ var Parser; } function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf) { nextToken(); - if (disallowOf && token() === 165 /* OfKeyword */) - return false; + if (disallowOf && token() === 165 /* OfKeyword */) return false; return (isBindingIdentifier() || token() === 19 /* OpenBraceToken */) && !scanner.hasPrecedingLineBreak(); } function isUsingDeclaration() { @@ -32893,11 +32855,10 @@ var Parser; const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; const isAsync = modifierFlags & 1024 /* Async */ ? 2 /* Await */ : 0 /* None */; const typeParameters = parseTypeParameters(); - if (modifierFlags & 32 /* Export */) - setAwaitContext( - /*value*/ - true - ); + if (modifierFlags & 32 /* Export */) setAwaitContext( + /*value*/ + true + ); const parameters = parseParameters(isGenerator | isAsync); const type = parseReturnType( 59 /* ColonToken */, @@ -33007,8 +32968,7 @@ var Parser; const body = parseFunctionBlockOrSemicolon(flags); const node = kind === 177 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body); node.typeParameters = typeParameters; - if (isSetAccessorDeclaration(node)) - node.type = type; + if (isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } function isClassMemberStart() { @@ -33122,8 +33082,7 @@ var Parser; } } while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { - if (modifier.kind === 126 /* StaticKeyword */) - hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; list = append(list, modifier); hasLeadingModifier = true; } @@ -33135,8 +33094,7 @@ var Parser; } if (hasTrailingDecorator) { while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { - if (modifier.kind === 126 /* StaticKeyword */) - hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; list = append(list, modifier); } } @@ -33251,11 +33209,10 @@ var Parser; parseExpected(86 /* ClassKeyword */); const name = parseNameOfClassDeclarationOrExpression(); const typeParameters = parseTypeParameters(); - if (some(modifiers, isExportModifier)) - setAwaitContext( - /*value*/ - true - ); + if (some(modifiers, isExportModifier)) setAwaitContext( + /*value*/ + true + ); const heritageClauses = parseHeritageClauses(); let members; if (parseExpected(19 /* OpenBraceToken */)) { @@ -33533,11 +33490,9 @@ var Parser; function parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks) { let namedBindings; if (!identifier || parseOptional(28 /* CommaToken */)) { - if (skipJsDocLeadingAsterisks) - scanner.setSkipJsDocLeadingAsterisks(true); + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(true); namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */); - if (skipJsDocLeadingAsterisks) - scanner.setSkipJsDocLeadingAsterisks(false); + if (skipJsDocLeadingAsterisks) scanner.setSkipJsDocLeadingAsterisks(false); } return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -33879,8 +33834,7 @@ var Parser; indent2 += text.length; } nextTokenJSDoc(); - while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) - ; + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) ; if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; indent2 = 0; @@ -33890,8 +33844,7 @@ var Parser; switch (token()) { case 60 /* AtToken */: removeTrailingWhitespace(comments); - if (!commentsPos) - commentsPos = getNodePos(); + if (!commentsPos) commentsPos = getNodePos(); addTag(parseTag(indent2)); state = 0 /* BeginningOfLine */; margin = void 0; @@ -33959,8 +33912,7 @@ var Parser; if (parts.length && trimmedComments.length) { parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); } - if (parts.length && tags) - Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); } @@ -34264,8 +34216,7 @@ var Parser; skipWhitespaceOrAsterisk(); if (token() === 19 /* OpenBraceToken */ && nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { const kind = scanner.getTokenValue(); - if (isJSDocLinkTag(kind)) - return kind; + if (isJSDocLinkTag(kind)) return kind; } } function isJSDocLinkTag(kind) { @@ -34854,8 +34805,7 @@ var IncrementalParser; } IncrementalParser2.updateSourceFile = updateSourceFile; function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { - if (!oldDirectives) - return newDirectives; + if (!oldDirectives) return newDirectives; let commentDirectives; let addedNewlyScannedDirectives = false; for (const directive of oldDirectives) { @@ -34877,8 +34827,7 @@ var IncrementalParser; addNewlyScannedDirectives(); return commentDirectives; function addNewlyScannedDirectives() { - if (addedNewlyScannedDirectives) - return; + if (addedNewlyScannedDirectives) return; addedNewlyScannedDirectives = true; if (!commentDirectives) { commentDirectives = newDirectives; @@ -35344,8 +35293,7 @@ function extractPragmas(pragmas, range, text) { } } function addPragmaForMatch(pragmas, range, kind, match) { - if (!match) - return; + if (!match) return; const name = match[1].toLowerCase(); const pragma = commentPragmas[name]; if (!pragma || !(pragma.kind & kind)) { @@ -35353,16 +35301,13 @@ function addPragmaForMatch(pragmas, range, kind, match) { } const args = match[2]; const argument = getNamedPragmaArguments(pragma, args); - if (argument === "fail") - return; + if (argument === "fail") return; pragmas.push({ name, args: { arguments: argument, range } }); return; } function getNamedPragmaArguments(pragma, text) { - if (!text) - return {}; - if (!pragma.args) - return {}; + if (!text) return {}; + if (!pragma.args) return {}; const args = text.trim().split(/\s+/); const argMap = {}; for (let i = 0; i < pragma.args.length; i++) { @@ -36005,6 +35950,20 @@ var commandOptionsWithoutBuild = [ defaultValueDescription: false, description: Diagnostics.Disable_emitting_comments }, + { + name: "noCheck", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, + transpileOptionValue: true, + defaultValueDescription: false, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + extraValidation() { + return [Diagnostics.Unknown_compiler_option_0, "noCheck"]; + } + }, { name: "noEmit", type: "boolean", @@ -36831,6 +36790,10 @@ var configDirTemplateSubstitutionOptions = optionDeclarations.filter( var configDirTemplateSubstitutionWatchOptions = optionsForWatch.filter( (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath ); +var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptionOfCustomType); +function isCommandLineOptionOfCustomType(option) { + return !isString(option.type); +} var optionsForBuild = [ { name: "verbose", @@ -37022,15 +36985,12 @@ function parseCommandLineWorker(diagnostics, commandLine, readFile) { const args = []; let pos = 0; while (true) { - while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) - pos++; - if (pos >= text.length) - break; + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++; + if (pos >= text.length) break; const start = pos; if (text.charCodeAt(start) === 34 /* doubleQuote */) { pos++; - while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) - pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++; if (pos < text.length) { args.push(text.substring(start + 1, pos)); pos++; @@ -37038,8 +36998,7 @@ function parseCommandLineWorker(diagnostics, commandLine, readFile) { errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); } } else { - while (text.charCodeAt(pos) > 32 /* space */) - pos++; + while (text.charCodeAt(pos) > 32 /* space */) pos++; args.push(text.substring(start, pos)); } } @@ -37062,14 +37021,12 @@ function parseOptionValue(args, i, diagnostics, opt, options, errors) { ); i++; } else { - if (optValue === "true") - i++; + if (optValue === "true") i++; errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name)); } } else { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name)); - if (optValue && !startsWith(optValue, "-")) - i++; + if (optValue && !startsWith(optValue, "-")) i++; } } else { if (!args[i] && opt.type !== "boolean") { @@ -37472,8 +37429,7 @@ function getCompilerOptionValueTypeString(option) { } function isCompilerOptionsValue(option, value) { if (option) { - if (isNullOrUndefined(value)) - return !option.disallowNullOrUndefined; + if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined; if (option.type === "list") { return isArray(value); } @@ -37546,17 +37502,13 @@ function optionMapToObject(optionMap) { }; } function filterSameAsDefaultInclude(specs) { - if (!length(specs)) - return void 0; - if (length(specs) !== 1) - return specs; - if (specs[0] === defaultIncludeSpec) - return void 0; + if (!length(specs)) return void 0; + if (length(specs) !== 1) return specs; + if (specs[0] === defaultIncludeSpec) return void 0; return specs; } function matchesSpecs(path, includeSpecs, excludeSpecs, host) { - if (!includeSpecs) - return returnTrue; + if (!includeSpecs) return returnTrue; const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); @@ -37682,8 +37634,7 @@ function generateTSConfig(options, fileNames, newLine) { for (const option of optionDeclarations) { if (isAllowedOptionForOutput(option)) { let listForCategory = categorizedOptions.get(option.category); - if (!listForCategory) - categorizedOptions.set(option.category, listForCategory = []); + if (!listForCategory) categorizedOptions.set(option.category, listForCategory = []); listForCategory.push(option); } } @@ -37812,8 +37763,7 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis options.configFilePath = configFileName && normalizeSlashes(configFileName); const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath); const configFileSpecs = getConfigFileSpecs(); - if (sourceFile) - sourceFile.configFileSpecs = configFileSpecs; + if (sourceFile) sourceFile.configFileSpecs = configFileSpecs; setConfigFileInOptions(options, sourceFile); return { options, @@ -37852,11 +37802,11 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis const excludeOfRaw = getSpecsFromRaw("exclude"); let isDefaultIncludeSpec = false; let excludeSpecs = toPropValue(excludeOfRaw); - if (excludeOfRaw === "no-prop" && raw.compilerOptions) { - const outDir = raw.compilerOptions.outDir; - const declarationDir = raw.compilerOptions.declarationDir; + if (excludeOfRaw === "no-prop") { + const outDir = options.outDir; + const declarationDir = options.declarationDir; if (outDir || declarationDir) { - excludeSpecs = [outDir, declarationDir].filter((d) => !!d); + excludeSpecs = filter([outDir, declarationDir], (d) => !!d); } } if (filesSpecs === void 0 && includeSpecs === void 0) { @@ -37970,8 +37920,7 @@ function handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, basePath) return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath); } function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, basePath) { - if (!options) - return options; + if (!options) return options; let result; for (const option of optionDeclarations2) { if (options[option.name] !== void 0) { @@ -37986,14 +37935,12 @@ function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, case "list": Debug.assert(option.element.isFilePath); const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value, basePath); - if (listResult) - setOptionValue(option, listResult); + if (listResult) setOptionValue(option, listResult); break; case "object": Debug.assert(option.name === "paths"); const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value, basePath); - if (objectResult) - setOptionValue(option, objectResult); + if (objectResult) setOptionValue(option, objectResult); break; default: Debug.fail("option type not supported"); @@ -38018,12 +37965,10 @@ function getSubstitutedPathWithConfigDirTemplate(value, basePath) { return getNormalizedAbsolutePath(value.replace(configDirTemplate, "./"), basePath); } function getSubstitutedStringArrayWithConfigDirTemplate(list, basePath) { - if (!list) - return list; + if (!list) return list; let result; list.forEach((element, index) => { - if (!startsWithConfigDirTemplate(element)) - return; + if (!startsWithConfigDirTemplate(element)) return; (result ?? (result = list.slice()))[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath); }); return result; @@ -38032,11 +37977,9 @@ function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike, basePa let result; const ownKeys = getOwnKeys(mapLike); ownKeys.forEach((key) => { - if (!isArray(mapLike[key])) - return; + if (!isArray(mapLike[key])) return; const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath); - if (!subStitution) - return; + if (!subStitution) return; (result ?? (result = assign({}, mapLike)))[key] = subStitution; }); return result; @@ -38090,16 +38033,11 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio } else { ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath)); } - if (result.include) - ownConfig.raw.include = result.include; - if (result.exclude) - ownConfig.raw.exclude = result.exclude; - if (result.files) - ownConfig.raw.files = result.files; - if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) - ownConfig.raw.compileOnSave = result.compileOnSave; - if (sourceFile && result.extendedSourceFiles) - sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); + if (result.include) ownConfig.raw.include = result.include; + if (result.exclude) ownConfig.raw.exclude = result.exclude; + if (result.files) ownConfig.raw.files = result.files; + if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave; + if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); ownConfig.options = assign(result.options, ownConfig.options); ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assign(result.watchOptions, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; } @@ -38110,8 +38048,7 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio const extendsRaw = extendedConfig.raw; let relativeDifference; const setPropertyInResultIfNotUndefined = (propertyName) => { - if (ownConfig.raw[propertyName]) - return; + if (ownConfig.raw[propertyName]) return; if (extendsRaw[propertyName]) { result[propertyName] = map(extendsRaw[propertyName], (path) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths( relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))), @@ -38198,19 +38135,14 @@ function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileNa } return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; function onPropertySet(keyText, value, propertyAssignment, parentOption, option) { - if (option && option !== extendsOptionDeclaration) - value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); if (parentOption == null ? void 0 : parentOption.name) { if (option) { let currentOption; - if (parentOption === compilerOptionsDeclaration) - currentOption = options; - else if (parentOption === watchOptionsDeclaration) - currentOption = watchOptions ?? (watchOptions = {}); - else if (parentOption === typeAcquisitionDeclaration) - currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); - else - Debug.fail("Unknown option"); + if (parentOption === compilerOptionsDeclaration) currentOption = options; + else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {}); + else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); + else Debug.fail("Unknown option"); currentOption[option.name] = value; } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) { if (parentOption.elementOptions) { @@ -38391,17 +38323,14 @@ function normalizeNonListOptionValue(option, basePath, value) { } function validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile) { var _a; - if (isNullOrUndefined(value)) - return void 0; + if (isNullOrUndefined(value)) return void 0; const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value); - if (!d) - return value; + if (!d) return value; errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d)); return void 0; } function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile) { - if (isNullOrUndefined(value)) - return void 0; + if (isNullOrUndefined(value)) return void 0; const key = value.toLowerCase(); const val = opt.type.get(key); if (val !== void 0) { @@ -38471,14 +38400,12 @@ function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, e } function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; - if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) - return false; + if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { - if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) - return false; + if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); @@ -38502,16 +38429,13 @@ function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, c function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); - if (!excludeRegex) - return false; - if (excludeRegex.test(pathToCheck)) - return true; + if (!excludeRegex) return false; + if (excludeRegex.test(pathToCheck)) return true; return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck)); } function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter((spec) => { - if (!isString(spec)) - return false; + if (!isString(spec)) return false; const diag2 = specToDiagnostic(spec, disallowTrailingRecursion); if (diag2 !== void 0) { errors.push(createDiagnostic(...diag2)); @@ -38550,8 +38474,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu const existingFlags = existingPath !== void 0 ? wildcardDirectories[existingPath] : void 0; if (existingFlags === void 0 || existingFlags < flags) { wildcardDirectories[existingPath !== void 0 ? existingPath : path] = flags; - if (existingPath === void 0) - wildCardKeyToPath.set(key, path); + if (existingPath === void 0) wildCardKeyToPath.set(key, path); if (flags === 1 /* Recursive */) { recursiveKeys.push(key); } @@ -38646,8 +38569,7 @@ function getDefaultValueForOption(option) { return {}; default: const value = firstOrUndefinedIterator(option.type.keys()); - if (value !== void 0) - return value; + if (value !== void 0) return value; return Debug.fail("Expected 'option.type' to have entries."); } } @@ -38691,14 +38613,10 @@ function removeIgnoredPackageId(r) { } function formatExtensions(extensions) { const result = []; - if (extensions & 1 /* TypeScript */) - result.push("TypeScript"); - if (extensions & 2 /* JavaScript */) - result.push("JavaScript"); - if (extensions & 4 /* Declaration */) - result.push("Declaration"); - if (extensions & 8 /* Json */) - result.push("JSON"); + if (extensions & 1 /* TypeScript */) result.push("TypeScript"); + if (extensions & 2 /* JavaScript */) result.push("JavaScript"); + if (extensions & 4 /* Declaration */) result.push("Declaration"); + if (extensions & 8 /* Json */) result.push("JSON"); return result.join(", "); } function resolvedTypeScriptOnly(resolved) { @@ -38711,8 +38629,7 @@ function resolvedTypeScriptOnly(resolved) { function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, alternateResult) { if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) { const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); - if (originalPath) - resolved = { ...resolved, path: resolvedFileName, originalPath }; + if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath }; } return createResolvedModuleWithFailedLookupLocations( resolved, @@ -38760,18 +38677,14 @@ function initializeResolutionField(value) { return value.length ? value : void 0; } function updateResolutionField(to, value) { - if (!(value == null ? void 0 : value.length)) - return to; - if (!(to == null ? void 0 : to.length)) - return value; + if (!(value == null ? void 0 : value.length)) return to; + if (!(to == null ? void 0 : to.length)) return value; to.push(...value); return to; } function initializeResolutionFieldForReadonlyCache(fromCache, value) { - if (!(fromCache == null ? void 0 : fromCache.length)) - return initializeResolutionField(value); - if (!value.length) - return fromCache.slice(); + if (!(fromCache == null ? void 0 : fromCache.length)) return initializeResolutionField(value); + if (!value.length) return fromCache.slice(); return [...fromCache, ...value]; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -38818,8 +38731,7 @@ function readPackageJsonMainField(jsonContent, baseDirectory, state) { } function readPackageJsonTypesVersionsField(jsonContent, state) { const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); - if (typesVersions === void 0) - return; + if (typesVersions === void 0) return; if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); } @@ -38827,8 +38739,7 @@ function readPackageJsonTypesVersionsField(jsonContent, state) { } function readPackageJsonTypesVersionPaths(jsonContent, state) { const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); - if (typesVersions === void 0) - return; + if (typesVersions === void 0) return; if (state.traceEnabled) { for (const key in typesVersions) { if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { @@ -38854,11 +38765,9 @@ function readPackageJsonTypesVersionPaths(jsonContent, state) { } var typeScriptVersion; function getPackageJsonTypesVersionsPaths(typesVersions) { - if (!typeScriptVersion) - typeScriptVersion = new Version(version); + if (!typeScriptVersion) typeScriptVersion = new Version(version); for (const key in typesVersions) { - if (!hasProperty(typesVersions, key)) - continue; + if (!hasProperty(typesVersions, key)) continue; const keyRange = VersionRange.tryParse(key); if (keyRange === void 0) { continue; @@ -38922,8 +38831,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil if (result) { if (traceEnabled) { trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); - if (redirectedReference) - trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); traceResult(result); } @@ -38985,8 +38893,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil if (resolved) { const { fileName, packageId } = resolved; let resolvedFileName = fileName, originalPath; - if (!options.preserveSymlinks) - ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); + if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); resolvedTypeReferenceDirective = { primary, resolvedFileName, @@ -39012,8 +38919,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); } } - if (traceEnabled) - traceResult(result); + if (traceEnabled) traceResult(result); return result; function traceResult(result2) { var _a; @@ -39201,8 +39107,7 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { const redirectsMap = /* @__PURE__ */ new Map(); const redirectsKeyToMap = /* @__PURE__ */ new Map(); let ownMap = /* @__PURE__ */ new Map(); - if (ownOptions) - redirectsMap.set(ownOptions, ownMap); + if (ownOptions) redirectsMap.set(ownOptions, ownMap); return { getMapOfCacheRedirects, getOrCreateMapOfCacheRedirects, @@ -39226,38 +39131,30 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { } function update(newOptions) { if (ownOptions !== newOptions) { - if (ownOptions) - ownMap = getOrCreateMap( - newOptions, - /*create*/ - true - ); - else - redirectsMap.set(newOptions, ownMap); + if (ownOptions) ownMap = getOrCreateMap( + newOptions, + /*create*/ + true + ); + else redirectsMap.set(newOptions, ownMap); ownOptions = newOptions; } } function getOrCreateMap(redirectOptions, create) { let result = redirectsMap.get(redirectOptions); - if (result) - return result; + if (result) return result; const key = getRedirectsCacheKey(redirectOptions); result = redirectsKeyToMap.get(key); if (!result) { if (ownOptions) { const ownKey = getRedirectsCacheKey(ownOptions); - if (ownKey === key) - result = ownMap; - else if (!redirectsKeyToMap.has(ownKey)) - redirectsKeyToMap.set(ownKey, ownMap); - } - if (create) - result ?? (result = /* @__PURE__ */ new Map()); - if (result) - redirectsKeyToMap.set(key, result); - } - if (result) - redirectsMap.set(redirectOptions, result); + if (ownKey === key) result = ownMap; + else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap); + } + if (create) result ?? (result = /* @__PURE__ */ new Map()); + if (result) redirectsKeyToMap.set(key, result); + } + if (result) redirectsMap.set(redirectOptions, result); return result; } function clear2() { @@ -39267,8 +39164,7 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { optionsToRedirectsKey.clear(); redirectsKeyToMap.clear(); if (ownOptions) { - if (ownKey) - optionsToRedirectsKey.set(ownOptions, ownKey); + if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey); redirectsMap.set(ownOptions, ownMap); } } @@ -39560,8 +39456,7 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } - if (result && result.resolvedModule) - (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); + if (result && result.resolvedModule) (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); (_c = perfLogger) == null ? void 0 : _c.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); if (cache && !cache.isReadonly) { cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); @@ -39585,8 +39480,7 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca } function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); - if (resolved) - return resolved.value; + if (resolved) return resolved.value; if (!isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { @@ -39787,8 +39681,7 @@ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, hos extensions = 8 /* Json */; } else if (compilerOptions.noDtsResolution) { extensions = 3 /* ImplementationFiles */; - if (getResolveJsonModule(compilerOptions)) - extensions |= 8 /* Json */; + if (getResolveJsonModule(compilerOptions)) extensions |= 8 /* Json */; } else { extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; } @@ -40175,10 +40068,8 @@ function getPeerDependenciesOfPackageJsonInfo(packageJsonInfo, state) { } function readPackageJsonPeerDependencies(packageJsonInfo, state) { const peerDependencies = readPackageJsonField(packageJsonInfo.contents.packageJsonContent, "peerDependencies", "object", state); - if (peerDependencies === void 0) - return void 0; - if (state.traceEnabled) - trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); + if (peerDependencies === void 0) return void 0; + if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled); const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator; let result = ""; @@ -40193,11 +40084,9 @@ function readPackageJsonPeerDependencies(packageJsonInfo, state) { if (peerPackageJson) { const version2 = peerPackageJson.contents.packageJsonContent.version; result += `+${key}@${version2}`; - if (state.traceEnabled) - trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2); + if (state.traceEnabled) trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2); } else { - if (state.traceEnabled) - trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key); + if (state.traceEnabled) trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key); } } } @@ -40214,13 +40103,11 @@ function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (existing !== void 0) { if (isPackageJsonInfo(existing)) { - if (traceEnabled) - trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); (_c = state.affectingLocations) == null ? void 0 : _c.push(packageJsonPath); return existing.packageDirectory === packageDirectory ? existing : { packageDirectory, contents: existing.contents }; } else { - if (existing.directoryExists && traceEnabled) - trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + if (existing.directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); (_d = state.failedLookupLocations) == null ? void 0 : _d.push(packageJsonPath); return void 0; } @@ -40232,16 +40119,14 @@ function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0, peerDependencies: void 0 } }; - if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) - state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath); return result; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } - if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) - state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists }); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists }); (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath); } } @@ -40307,8 +40192,7 @@ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFail } } const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); - if (packageFileResult) - return packageFileResult; + if (packageFileResult) return packageFileResult; if (!(state.features & 32 /* EsmMode */)) { return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } @@ -40474,18 +40358,12 @@ function comparePatternKeys(a, b) { const bPatternIndex = b.indexOf("*"); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - if (baseLenA > baseLenB) - return -1; - if (baseLenB > baseLenA) - return 1; - if (aPatternIndex === -1) - return 1; - if (bPatternIndex === -1) - return -1; - if (a.length > b.length) - return -1; - if (b.length > a.length) - return 1; + if (baseLenA > baseLenB) return -1; + if (baseLenB > baseLenA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; return 0; } function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { @@ -40537,11 +40415,9 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe } } function matchesPatternWithTrailer(target, name) { - if (endsWith(target, "*")) - return false; + if (endsWith(target, "*")) return false; const starPos = target.indexOf("*"); - if (starPos === -1) - return false; + if (starPos === -1) return false; return startsWith(name, target.substring(0, starPos)) && endsWith(name, target.substring(starPos + 1)); } } @@ -40625,8 +40501,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec } const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports); - if (inputLink) - return inputLink; + if (inputLink) return inputLink; return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, finalPath, @@ -40690,8 +40565,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec ); function toAbsolutePath(path) { var _a, _b; - if (path === void 0) - return path; + if (path === void 0) return path; return getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); } function combineDirectoryPath(root, dir) { @@ -40737,8 +40611,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec if (fileExtensionIs(possibleInputBase, ext)) { const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase); for (const possibleExt of inputExts) { - if (!extensionIsOk(extensions, possibleExt)) - continue; + if (!extensionIsOk(extensions, possibleExt)) continue; const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( @@ -40773,13 +40646,10 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec } } function isApplicableVersionedTypesKey(conditions, key) { - if (!conditions.includes("types")) - return false; - if (!startsWith(key, "types@")) - return false; + if (!conditions.includes("types")) return false; + if (!startsWith(key, "types@")) return false; const range = VersionRange.tryParse(key.substring("types@".length)); - if (!range) - return false; + if (!range) return false; return range.test(version); } function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { @@ -40815,8 +40685,7 @@ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, if (priorityExtensions) { traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions)); const result = lookup(priorityExtensions); - if (result) - return result; + if (result) return result; } if (secondaryExtensions && !typesScopeOnly) { traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions)); @@ -41061,12 +40930,10 @@ function classicNameResolver(moduleName, containingFile, compilerOptions, host, state )); }); - if (resolved2) - return resolved2; + if (resolved2) return resolved2; if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) { let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); - if (extensions & 4 /* Declaration */) - resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); + if (extensions & 4 /* Declaration */) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); return resolved3; } } else { @@ -41082,8 +40949,7 @@ function classicNameResolver(moduleName, containingFile, compilerOptions, host, } } function resolveFromTypeRoot(moduleName, state) { - if (!state.compilerOptions.typeRoots) - return; + if (!state.compilerOptions.typeRoots) return; for (const typeRoot of state.compilerOptions.typeRoots) { const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state); const directoryExists = directoryProbablyExists(typeRoot, state.host); @@ -41102,8 +40968,7 @@ function resolveFromTypeRoot(moduleName, state) { return toSearchResult(withPackageId(packageInfo, resolvedFromFile, state)); } const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state); - if (resolved) - return toSearchResult(resolved); + if (resolved) return toSearchResult(resolved); } } function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { @@ -41508,8 +41373,7 @@ function createBinder() { } if (!symbol) { symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - if (isReplaceableByMethod) - symbol.isReplaceableByMethod = true; + if (isReplaceableByMethod) symbol.isReplaceableByMethod = true; } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { return symbol; } else if (symbol.flags & excludes) { @@ -41585,8 +41449,7 @@ function createBinder() { ); } } else { - if (isJSDocTypeAlias(node)) - Debug.assert(isInJSFile(node)); + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) { if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -41620,17 +41483,12 @@ function createBinder() { if (node.parent && isModuleDeclaration(node)) { node = node.parent; } - if (!isJSDocTypeAlias(node)) - return false; - if (!isJSDocEnumTag(node) && !!node.fullName) - return true; + if (!isJSDocTypeAlias(node)) return false; + if (!isJSDocEnumTag(node) && !!node.fullName) return true; const declName = getNameOfDeclaration(node); - if (!declName) - return false; - if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) - return true; - if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) - return true; + if (!declName) return false; + if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true; + if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true; return false; } function bindContainer(node, containerFlags) { @@ -41683,8 +41541,7 @@ function createBinder() { node.flags &= ~5632 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) { node.flags |= 512 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 1024 /* HasExplicitReturn */; + if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } if (node.kind === 307 /* SourceFile */) { @@ -42731,8 +42588,7 @@ function createBinder() { case 175 /* ClassStaticBlockDeclaration */: case 265 /* TypeAliasDeclaration */: case 200 /* MappedType */: - if (container.locals) - Debug.assertNode(container, canHaveLocals); + if (container.locals) Debug.assertNode(container, canHaveLocals); return declareSymbol( container.locals, /*parent*/ @@ -43102,8 +42958,7 @@ function createBinder() { return; } setParent(node, parent); - if (tracing) - node.tracingPath = file.path; + if (tracing) node.tracingPath = file.path; const saveInStrictMode = inStrictMode; bindWorker(node); if (node.kind > 165 /* LastToken */) { @@ -43118,8 +42973,7 @@ function createBinder() { parent = saveParent; } else { const saveParent = parent; - if (node.kind === 1 /* EndOfFileToken */) - parent = node; + if (node.kind === 1 /* EndOfFileToken */) parent = node; bindJSDoc(node); parent = saveParent; } @@ -44157,8 +44011,7 @@ function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignatu } visitedTypes[type.id] = type; const shouldBail = visitSymbol(type.symbol); - if (shouldBail) - return; + if (shouldBail) return; if (type.flags & 524288 /* Object */) { const objectType = type; const objectFlags = objectType.objectFlags; @@ -44310,10 +44163,8 @@ function getModuleSpecifierPreferences({ importModuleSpecifierPreference, import }; function getPreferredEnding(resolutionMode) { if (oldImportSpecifier !== void 0) { - if (hasJSFileExtension(oldImportSpecifier)) - return 2 /* JsExtension */; - if (endsWith(oldImportSpecifier, "/index")) - return 1 /* Index */; + if (hasJSFileExtension(oldImportSpecifier)) return 2 /* JsExtension */; + if (endsWith(oldImportSpecifier, "/index")) return 1 /* Index */; } return getModuleSpecifierEndingPreference( importModuleSpecifierEnding, @@ -44331,7 +44182,7 @@ function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile } const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options); - return [cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache]; + return [cached == null ? void 0 : cached.kind, cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache]; } function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) { return getModuleSpecifiersWithCacheInfo( @@ -44349,19 +44200,16 @@ function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSo function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { let computedWithoutCache = false; const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); - if (ambient) - return { moduleSpecifiers: [ambient], computedWithoutCache }; - let [specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( + if (ambient) return { kind: "ambient", moduleSpecifiers: [ambient], computedWithoutCache }; + let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( moduleSymbol, importingSourceFile, host, userPreferences, options ); - if (specifiers) - return { moduleSpecifiers: specifiers, computedWithoutCache }; - if (!moduleSourceFile) - return { moduleSpecifiers: emptyArray, computedWithoutCache }; + if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache }; + if (!moduleSourceFile) return { kind: void 0, moduleSpecifiers: emptyArray, computedWithoutCache }; computedWithoutCache = true; modulePaths || (modulePaths = getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options)); const result = computeModuleSpecifiers( @@ -44373,8 +44221,8 @@ function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions options, forAutoImport ); - cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, modulePaths, result); - return { moduleSpecifiers: result, computedWithoutCache }; + cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers); + return result; } function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { const info = getInfo(importingSourceFile.fileName, host); @@ -44382,8 +44230,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach( host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), (reason) => { - if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) - return void 0; + if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0; const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index); const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile); if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) { @@ -44394,8 +44241,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi } )); if (existingSpecifier) { - const moduleSpecifiers = [existingSpecifier]; - return moduleSpecifiers; + return { kind: void 0, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true }; } const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules); let nodeModulesSpecifiers; @@ -44416,7 +44262,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi ) : void 0; nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); if (specifier && modulePath.isRedirect) { - return nodeModulesSpecifiers; + return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; } if (!specifier) { const local = getLocalModuleSpecifier( @@ -44445,7 +44291,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi } } } - return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? redirectPathsSpecifiers : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers : Debug.checkDefined(relativeSpecifiers); + return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: Debug.checkDefined(relativeSpecifiers), computedWithoutCache: true }; } function getInfo(importingSourceFileName, host) { importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory()); @@ -44505,17 +44351,14 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative; } function packageJsonPathsAreEqual(a, b, ignoreCase) { - if (a === b) - return true; - if (a === void 0 || b === void 0) - return false; + if (a === b) return true; + if (a === void 0 || b === void 0) return false; return comparePaths(a, b, ignoreCase) === 0 /* EqualTo */; } function countPathComponents(path) { let count = 0; for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) { - if (path.charCodeAt(i) === 47 /* slash */) - count++; + if (path.charCodeAt(i) === 47 /* slash */) count++; } return count; } @@ -44542,15 +44385,13 @@ function forEachFileNameOfModule(importingFileName, importedFileName, host, pref let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath); if (!preferSymlinks) { const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); - if (result2) - return result2; + if (result2) return result2; } const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd); const result = symlinkedDirectories && forEachAncestorDirectory(getDirectoryPath(fullImportedFileName), (realPathDirectory) => { const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); - if (!symlinkDirectories) - return void 0; + if (!symlinkDirectories) return void 0; if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { return false; } @@ -44563,8 +44404,7 @@ function forEachFileNameOfModule(importingFileName, importedFileName, host, pref const option = resolvePath(symlinkDirectory, relative); const result2 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; - if (result2) - return result2; + if (result2) return result2; } }); }); @@ -44637,8 +44477,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, sortedPaths.push(...pathsInDirectory); } const newDirectory = getDirectoryPath(directory); - if (newDirectory === directory) - break; + if (newDirectory === directory) break; directory = newDirectory; } if (allFileNames.size) { @@ -44646,8 +44485,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, allFileNames.entries(), ([fileName, { isRedirect, isInNodeModules }]) => ({ path: fileName, isRedirect, isInNodeModules }) ); - if (remainingPaths.length > 1) - remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); + if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push(...remainingPaths); } return sortedPaths; @@ -44662,20 +44500,15 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { } const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => { var _a2, _b, _c, _d; - if (!isModuleDeclaration(d)) - return; + if (!isModuleDeclaration(d)) return; const topNamespace = getTopNamespace(d); - if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) - return; + if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; - if (!exportAssignment) - return; + if (!exportAssignment) return; const exportSymbol = checker.getSymbolAtLocation(exportAssignment); - if (!exportSymbol) - return; + if (!exportSymbol) return; const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; - if (originalExportSymbol === d.symbol) - return topNamespace.parent.parent; + if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; function getTopNamespace(namespaceDeclaration) { while (namespaceDeclaration.flags & 8 /* NestedNamespace */) { namespaceDeclaration = namespaceDeclaration.parent; @@ -44878,8 +44711,7 @@ function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, } const conditions = getConditions(options, importMode); return (_c = forEach(getOwnKeys(imports), (k) => { - if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) - return void 0; + if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) return void 0; const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; return tryGetModuleNameFromExportsOrImports( options, @@ -44940,8 +44772,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa isPackageRootPath = true; break; } - if (!moduleFileName) - moduleFileName = moduleFileToTry; + if (!moduleFileName) moduleFileName = moduleFileToTry; packageRootIndex = path.indexOf(directorySeparator, packageRootIndex + 1); if (packageRootIndex === -1) { moduleSpecifier = processEnding(moduleFileName, allowedEndings, options, host); @@ -45018,8 +44849,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa } } function tryGetAnyFileFromPath(host, path) { - if (!host.fileExists) - return; + if (!host.fileExists) return; const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }])); for (const e of extensions) { const fullPath = path + e; @@ -45074,8 +44904,7 @@ function processEnding(fileName, allowedEndings, options, host) { } function tryGetRealFileNameForNonJsDeclarationFileName(fileName) { const baseName = getBaseFileName(fileName); - if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) - return void 0; + if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0; const noExtension = removeExtension(fileName, ".ts" /* Ts */); const ext = noExtension.substring(noExtension.lastIndexOf(".")); return noExtension.substring(0, noExtension.indexOf(".d.")) + ext; @@ -45279,9 +45108,6 @@ function createTypeChecker(host) { deferredDiagnosticsCallbacks.push(arg); }; var cancellationToken; - var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); - var requestedExternalEmitHelpers; - var externalHelpersModule; var scanner; var Symbol12 = objectAllocator.getSymbolConstructor(); var Type7 = objectAllocator.getTypeConstructor(); @@ -45318,7 +45144,6 @@ function createTypeChecker(host) { var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, { isEntityNameVisible, isExpandoFunctionDeclaration, - isNonNarrowedBindableName, getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration, requiresAddingImplicitUndefined, isUndefinedIdentifierExpression(node) { @@ -45399,8 +45224,7 @@ function createTypeChecker(host) { getTypeOfSymbol, getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => { const parameter = getParseTreeNode(parameterIn, isParameter); - if (parameter === void 0) - return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent)); return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName)); }, @@ -45426,6 +45250,7 @@ function createTypeChecker(host) { getBaseTypes, getBaseTypeOfLiteralType, getWidenedType, + getWidenedLiteralType, getTypeFromTypeNode: (nodeIn) => { const node = getParseTreeNode(nodeIn, isTypeNode); return node ? getTypeFromTypeNode(node) : errorType; @@ -45577,6 +45402,7 @@ function createTypeChecker(host) { getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver, + requiresAddingImplicitUndefined, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule, forEachExportAndPropertyOfModule, @@ -45650,8 +45476,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ); - if (type === emptyGenericType) - return void 0; + if (type === emptyGenericType) return void 0; return type; }, isSymbolAccessible, @@ -45741,7 +45566,8 @@ function createTypeChecker(host) { getTypeOnlyAliasDeclaration, getMemberOverrideModifierStatus, isTypeParameterPossiblyReferenced, - typeHasCallOrConstructSignatures + typeHasCallOrConstructSignatures, + getSymbolFlags }; function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) { const candidatesSet = /* @__PURE__ */ new Set(); @@ -46284,8 +46110,7 @@ function createTypeChecker(host) { return key ? cachedTypes.get(key) : void 0; } function setCachedType(key, type) { - if (key) - cachedTypes.set(key, type); + if (key) cachedTypes.set(key, type); return type; } function getJsxNamespace(location) { @@ -46358,8 +46183,8 @@ function createTypeChecker(host) { void 0 ); } - function getEmitResolver(sourceFile, cancellationToken2) { - getDiagnostics(sourceFile, cancellationToken2); + function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) { + if (!skipDiagnostics) getDiagnostics(sourceFile, cancellationToken2); return emitResolver; } function lookupOrIssueError(location, message, ...args) { @@ -46459,38 +46284,22 @@ function createTypeChecker(host) { } function getExcludedSymbolFlags(flags) { let result = 0; - if (flags & 2 /* BlockScopedVariable */) - result |= 111551 /* BlockScopedVariableExcludes */; - if (flags & 1 /* FunctionScopedVariable */) - result |= 111550 /* FunctionScopedVariableExcludes */; - if (flags & 4 /* Property */) - result |= 0 /* PropertyExcludes */; - if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; - if (flags & 16 /* Function */) - result |= 110991 /* FunctionExcludes */; - if (flags & 32 /* Class */) - result |= 899503 /* ClassExcludes */; - if (flags & 64 /* Interface */) - result |= 788872 /* InterfaceExcludes */; - if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; - if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; - if (flags & 512 /* ValueModule */) - result |= 110735 /* ValueModuleExcludes */; - if (flags & 8192 /* Method */) - result |= 103359 /* MethodExcludes */; - if (flags & 32768 /* GetAccessor */) - result |= 46015 /* GetAccessorExcludes */; - if (flags & 65536 /* SetAccessor */) - result |= 78783 /* SetAccessorExcludes */; - if (flags & 262144 /* TypeParameter */) - result |= 526824 /* TypeParameterExcludes */; - if (flags & 524288 /* TypeAlias */) - result |= 788968 /* TypeAliasExcludes */; - if (flags & 2097152 /* Alias */) - result |= 2097152 /* AliasExcludes */; + if (flags & 2 /* BlockScopedVariable */) result |= 111551 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) result |= 111550 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) result |= 110991 /* FunctionExcludes */; + if (flags & 32 /* Class */) result |= 899503 /* ClassExcludes */; + if (flags & 64 /* Interface */) result |= 788872 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) result |= 103359 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) result |= 46015 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) result |= 78783 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) result |= 526824 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) result |= 788968 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; } function recordMergedSymbol(target, source) { @@ -46504,14 +46313,10 @@ function createTypeChecker(host) { const result = createSymbol(symbol.flags, symbol.escapedName); result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = new Map(symbol.members); - if (symbol.exports) - result.exports = new Map(symbol.exports); + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -46525,7 +46330,12 @@ function createTypeChecker(host) { if (resolvedTarget === unknownSymbol) { return source; } - target = cloneSymbol(resolvedTarget); + if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & 67108864 /* Assignment */) { + target = cloneSymbol(resolvedTarget); + } else { + reportMergeSymbolError(target, source); + return source; + } } if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; @@ -46536,13 +46346,11 @@ function createTypeChecker(host) { } addRange(target.declarations, source.declarations); if (source.members) { - if (!target.members) - target.members = createSymbolTable(); + if (!target.members) target.members = createSymbolTable(); mergeSymbolTable(target.members, source.members, unidirectional); } if (source.exports) { - if (!target.exports) - target.exports = createSymbolTable(); + if (!target.exports) target.exports = createSymbolTable(); mergeSymbolTable(target.exports, source.exports, unidirectional); } if (!unidirectional) { @@ -46557,31 +46365,30 @@ function createTypeChecker(host) { ); } } else { - const isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - const isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + reportMergeSymbolError(target, source); + } + return target; + function reportMergeSymbolError(target2, source2) { + const isEitherEnum = !!(target2.flags & 384 /* Enum */ || source2.flags & 384 /* Enum */); + const isEitherBlockScoped = !!(target2.flags & 2 /* BlockScopedVariable */ || source2.flags & 2 /* BlockScopedVariable */); const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; - const sourceSymbolFile = source.declarations && getSourceFileOfNode(source.declarations[0]); - const targetSymbolFile = target.declarations && getSourceFileOfNode(target.declarations[0]); + const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]); + const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]); const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs); const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs); - const symbolName2 = symbolToString(source); + const symbolName2 = symbolToString(source2); if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() })); const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); - if (!isSourcePlainJs) - addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); - if (!isTargetPlainJs) - addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2); + if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2); } else { - if (!isSourcePlainJs) - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName2, target); - if (!isTargetPlainJs) - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source); + if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2); + if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2); } } - return target; function addDuplicateLocations(locs, symbol) { if (symbol.declarations) { for (const decl of symbol.declarations) { @@ -46608,21 +46415,17 @@ function createTypeChecker(host) { /*isPrototypeAssignment*/ false ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode; - if (adjustedNode === errorNode) - continue; + if (adjustedNode === errorNode) continue; err.relatedInformation = err.relatedInformation || []; const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2); const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here); - if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) - continue; + if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) continue; addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage); } } function combineSymbolTables(first2, second) { - if (!(first2 == null ? void 0 : first2.size)) - return second; - if (!(second == null ? void 0 : second.size)) - return first2; + if (!(first2 == null ? void 0 : first2.size)) return second; + if (!(second == null ? void 0 : second.size)) return first2; const combined = createSymbolTable(); mergeSymbolTable(combined, first2); mergeSymbolTable(combined, second); @@ -46698,8 +46501,7 @@ function createTypeChecker(host) { } } function getSymbolLinks(symbol) { - if (symbol.flags & 33554432 /* Transient */) - return symbol.links; + if (symbol.flags & 33554432 /* Transient */) return symbol.links; const id = getSymbolId(symbol); return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks()); } @@ -46711,7 +46513,6 @@ function createTypeChecker(host) { if (meaning) { const symbol = getMergedSymbol(symbols.get(name)); if (symbol) { - Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -46931,6 +46732,7 @@ function createTypeChecker(host) { ); const message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1; const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); + diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg)); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { addRelatedInfo( @@ -46998,8 +46800,7 @@ function createTypeChecker(host) { }); } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { - if (!typeOnlyDeclaration) - return diagnostic; + if (!typeOnlyDeclaration) return diagnostic; return addRelatedInfo( diagnostic, createDiagnosticForNode( @@ -47248,8 +47049,7 @@ function createTypeChecker(host) { const declaration = (_a = result.declarations) == null ? void 0 : _a.find( (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */ ); - if (declaration === void 0) - return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); + if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { let diagnosticMessage; const declarationName = declarationNameToString(getNameOfDeclaration(declaration)); @@ -47573,12 +47373,9 @@ function createTypeChecker(host) { Debug.assert(valueSymbol.declarations || typeSymbol.declarations); result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues); result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = new Map(typeSymbol.members); - if (valueSymbol.exports) - result.exports = new Map(valueSymbol.exports); + if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) result.members = new Map(typeSymbol.members); + if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports); return result; } function getExportOfModule(symbol, name, specifier, dontResolveAlias) { @@ -47859,8 +47656,7 @@ function createTypeChecker(host) { } } function isNonLocalAlias(symbol, excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */) { - if (!symbol) - return false; + if (!symbol) return false; return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { @@ -47872,8 +47668,7 @@ function createTypeChecker(host) { if (!links.aliasTarget) { links.aliasTarget = resolvingSymbol; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); const target = getTargetOfAliasDeclaration(node); if (links.aliasTarget === resolvingSymbol) { links.aliasTarget = target || unknownSymbol; @@ -47928,8 +47723,7 @@ function createTypeChecker(host) { return flags; } function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) { - if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) - return false; + if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false; const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration); if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) { const links2 = getSymbolLinks(sourceSymbol); @@ -47957,10 +47751,22 @@ function createTypeChecker(host) { return !!aliasDeclarationLinks.typeOnlyDeclaration; } function getTypeOnlyAliasDeclaration(symbol, include) { + var _a; if (!(symbol.flags & 2097152 /* Alias */)) { return void 0; } const links = getSymbolLinks(symbol); + if (links.typeOnlyDeclaration === void 0) { + links.typeOnlyDeclaration = false; + const resolved = resolveSymbol(symbol); + markSymbolOfAliasDeclarationIfTypeOnly( + (_a = symbol.declarations) == null ? void 0 : _a[0], + getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol), + resolved, + /*overwriteEmpty*/ + true + ); + } if (include === void 0) { return links.typeOnlyDeclaration || void 0; } @@ -47970,44 +47776,6 @@ function createTypeChecker(host) { } return void 0; } - function markExportAsReferenced(node) { - if (!canCollectSymbolAliasAccessabilityData) { - return; - } - const symbol = getSymbolOfDeclaration(node); - const target = resolveAlias(symbol); - if (target) { - const markAlias = target === unknownSymbol || getSymbolFlags( - symbol, - /*excludeTypeOnlyMeanings*/ - true - ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - function markAliasSymbolAsReferenced(symbol) { - Debug.assert(canCollectSymbolAliasAccessabilityData); - const links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); - if (isInternalModuleImportEqualsDeclaration(node)) { - if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { - checkExpressionCached(node.moduleReference); - } - } - } - } - function markConstEnumAliasAsReferenced(symbol) { - const links = getSymbolLinks(symbol); - if (!links.constEnumReferenced) { - links.constEnumReferenced = true; - } - } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -48160,7 +47928,6 @@ function createTypeChecker(host) { } else { Debug.assertNever(name, "Unknown entity name kind."); } - Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly( getAliasDeclarationFromName(name), @@ -48489,8 +48256,7 @@ function createTypeChecker(host) { merged.exports = createSymbolTable(); } moduleSymbol.exports.forEach((s, name) => { - if (name === "export=" /* ExportEquals */) - return; + if (name === "export=" /* ExportEquals */) return; merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); }); if (merged === exported) { @@ -48544,14 +48310,10 @@ function createTypeChecker(host) { result.parent = symbol.parent; result.links.target = symbol; result.links.originatingImport = referenceParent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = new Map(symbol.members); - if (symbol.exports) - result.exports = new Map(symbol.exports); + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); const resolvedModuleType = resolveStructuredTypeMembers(moduleType); result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos); return result; @@ -48625,11 +48387,9 @@ function createTypeChecker(host) { return links.resolvedExports; } function extendExportSymbols(target, source, lookupTable, exportNode) { - if (!source) - return; + if (!source) return; source.forEach((sourceSymbol, id) => { - if (id === "default" /* Default */) - return; + if (id === "default" /* Default */) return; const targetSymbol = target.get(id); if (!targetSymbol) { target.set(id, sourceSymbol); @@ -48739,19 +48499,16 @@ function createTypeChecker(host) { } if (containingFile && containingFile.imports) { for (const importRef of containingFile.imports) { - if (nodeIsSynthesized(importRef)) - continue; + if (nodeIsSynthesized(importRef)) continue; const resolvedModule = resolveExternalModuleName( enclosingDeclaration, importRef, /*ignoreErrors*/ true ); - if (!resolvedModule) - continue; + if (!resolvedModule) continue; const ref = getAliasForSymbolInContainer(resolvedModule, symbol); - if (!ref) - continue; + if (!ref) continue; results = append(results, resolvedModule); } if (length(results)) { @@ -48764,12 +48521,10 @@ function createTypeChecker(host) { } const otherFiles = host.getSourceFiles(); for (const file of otherFiles) { - if (!isExternalModule(file)) - continue; + if (!isExternalModule(file)) continue; const sym = getSymbolOfDeclaration(file); const ref = getAliasForSymbolInContainer(sym, symbol); - if (!ref) - continue; + if (!ref) continue; results = append(results, sym); } return links.extendedContainers = results || emptyArray; @@ -48954,21 +48709,17 @@ function createTypeChecker(host) { resolved.callSignatures = callSignatures; resolved.constructSignatures = constructSignatures; resolved.indexInfos = indexInfos; - if (members !== emptySymbols) - resolved.properties = getNamedMembers(members); + if (members !== emptySymbols) resolved.properties = getNamedMembers(members); return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos); } function getResolvedTypeWithoutAbstractConstructSignatures(type) { - if (type.constructSignatures.length === 0) - return type; - if (type.objectTypeWithoutAbstractConstructSignatures) - return type.objectTypeWithoutAbstractConstructSignatures; + if (type.constructSignatures.length === 0) return type; + if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures; const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */)); - if (type.constructSignatures === constructSignatures) - return type; + if (type.constructSignatures === constructSignatures) return type; const typeCopy = createAnonymousType( type.symbol, type.members, @@ -49203,8 +48954,7 @@ function createTypeChecker(host) { return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) { - if (!length(symbols)) - return; + if (!length(symbols)) return; let hadAccessibleChain; let earlyModuleBail = false; for (const symbol of symbols) { @@ -49382,7 +49132,14 @@ function createTypeChecker(host) { ).accessibility === 0 /* Accessible */) { return { accessibility: 0 /* Accessible */ }; } - return symbol && hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || { + if (!symbol) { + return { + accessibility: 3 /* NotResolved */, + errorSymbolName: getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || { accessibility: 1 /* NotAccessible */, errorSymbolName: getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -49446,8 +49203,7 @@ function createTypeChecker(host) { function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) { const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); - if (typeNode === void 0) - return Debug.fail("should always get typenode"); + if (typeNode === void 0) return Debug.fail("should always get typenode"); const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( @@ -49490,6 +49246,9 @@ function createTypeChecker(host) { function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */)); } + function getTypeFromTypeNodeWithoutContext(node) { + return getTypeFromTypeNode(node); + } function createNodeBuilder() { return { typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typeToTypeNodeHelper(type, context)), @@ -49518,10 +49277,17 @@ function createTypeChecker(host) { symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToNode(symbol, context, meaning)) }; + function getTypeFromTypeNode2(context, node, noMappedTypes) { + const type = getTypeFromTypeNodeWithoutContext(node); + if (!context.mapper) return type; + const mappedType = instantiateType(type, context.mapper); + return noMappedTypes && mappedType !== type ? void 0 : mappedType; + } function setTextRange2(context, range, location) { - if (!nodeIsSynthesized(range) && !(range.flags & 16 /* Synthesized */) && (!context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(range))) { + if (!nodeIsSynthesized(range) || !(range.flags & 16 /* Synthesized */) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) { range = factory.cloneNode(range); } + if (range === location) return range; if (!location) { return range; } @@ -49562,7 +49328,7 @@ function createTypeChecker(host) { } const clone = tryReuseExistingNonParameterTypeNode(context, typeNode, type, host2); if (clone) { - if (addUndefined && !someType(getTypeFromTypeNode(typeNode), (t) => !!(t.flags & 32768 /* Undefined */))) { + if (addUndefined && !someType(getTypeFromTypeNode2(context, typeNode), (t) => !!(t.flags & 32768 /* Undefined */))) { return factory.createUnionTypeNode([clone, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } return clone; @@ -49575,8 +49341,13 @@ function createTypeChecker(host) { } return void 0; } - function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType) { - if (typeNodeIsEquivalentToType(existing, host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { + function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + )) { + if (annotationType && typeNodeIsEquivalentToType(host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { const result = tryReuseExistingTypeNodeHelper(context, existing); if (result) { return result; @@ -49588,8 +49359,7 @@ function createTypeChecker(host) { if (context.flags & 1073741824 /* WriteComputedProps */) { if (symbol.valueDeclaration) { const name = getNameOfDeclaration(symbol.valueDeclaration); - if (name && isComputedPropertyName(name)) - return name; + if (name && isComputedPropertyName(name)) return name; } const nameType = getSymbolLinks(symbol).nameType; if (nameType && nameType.flags & (1024 /* EnumLiteral */ | 8192 /* UniqueESSymbol */)) { @@ -49600,7 +49370,6 @@ function createTypeChecker(host) { return symbolToExpression(symbol, context, meaning); } function withContext(enclosingDeclaration, flags, tracker, cb) { - Debug.assert(enclosingDeclaration === void 0 || (enclosingDeclaration.flags & 16 /* Synthesized */) === 0); const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : flags & 134217728 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; const context = { enclosingDeclaration, @@ -49614,7 +49383,19 @@ function createTypeChecker(host) { inferTypeParameters: void 0, approximateLength: 0, trackedSymbols: void 0, - bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)) + bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)), + truncating: false, + usedSymbolNames: void 0, + remappedSymbolNames: void 0, + remappedSymbolReferences: void 0, + reverseMappedStack: void 0, + mustCreateTypeParameterSymbolList: true, + typeParameterSymbolList: void 0, + mustCreateTypeParametersNamesLookups: true, + typeParameterNames: void 0, + typeParameterNamesByText: void 0, + typeParameterNamesByTextNextNameCount: void 0, + mapper: void 0 }; context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); const resultingNode = cb(context); @@ -49624,8 +49405,7 @@ function createTypeChecker(host) { return context.encounteredError ? void 0 : resultingNode; } function checkTruncationLength(context) { - if (context.truncating) - return context.truncating; + if (context.truncating) return context.truncating; return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { @@ -49776,8 +49556,7 @@ function createTypeChecker(host) { } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) - return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes); if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { return factory.createArrayTypeNode(typeArgumentNodes[0]); } @@ -49907,8 +49686,8 @@ function createTypeChecker(host) { context.inferTypeParameters = type2.root.inferTypeParameters; const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context); context.inferTypeParameters = saveInferTypeParameters2; - const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.trueType), newMapper)); - const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.falseType), newMapper)); + const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper)); + const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper)); return factory.createConditionalTypeNode( checkTypeNode, factory.createInferTypeNode(factory.createTypeParameterDeclaration( @@ -49991,7 +49770,7 @@ function createTypeChecker(host) { context.approximateLength += 10; const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */); if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { - const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); + const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); return factory.createConditionalTypeNode( typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration( @@ -50357,8 +50136,7 @@ function createTypeChecker(host) { typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context)); } for (const signature of resolvedType.constructSignatures) { - if (signature.flags & 4 /* Abstract */) - continue; + if (signature.flags & 4 /* Abstract */) continue; typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context)); } for (const info of resolvedType.indexInfos) { @@ -50445,7 +50223,8 @@ function createTypeChecker(host) { const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */); const getterSignature = getSignatureFromDeclaration(getterDeclaration); typeElements.push( - setCommentRange( + setCommentRange2( + context, signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }), getterDeclaration ) @@ -50453,7 +50232,8 @@ function createTypeChecker(host) { const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */); const setterSignature = getSignatureFromDeclaration(setterDeclaration); typeElements.push( - setCommentRange( + setCommentRange2( + context, signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }), setterDeclaration ) @@ -50511,11 +50291,17 @@ function createTypeChecker(host) { setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } } else if (propertySymbol.valueDeclaration) { - setCommentRange(node, propertySymbol.valueDeclaration); + setCommentRange2(context, node, propertySymbol.valueDeclaration); } return node; } } + function setCommentRange2(context, node, range) { + if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) { + return setCommentRange(node, range); + } + return node; + } function mapToTypeNodes(types, context, isBareList) { if (some(types)) { if (checkTruncationLength(context)) { @@ -50612,22 +50398,22 @@ function createTypeChecker(host) { } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a; - const flags = context.flags; - context.flags &= ~256 /* SuppressAnyReturnType */; - context.approximateLength += 3; let typeParameters; let typeArguments; - if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { - typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); - } else { - typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); - } const expandedParams = getExpandedParameters( signature, /*skipUnionExpanding*/ true )[0]; - const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters); + const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper); + context.approximateLength += 3; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); + } else { + typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); + } + const flags = context.flags; + context.flags &= ~256 /* SuppressAnyReturnType */; const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */)); const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { @@ -50725,15 +50511,18 @@ function createTypeChecker(host) { return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).typeParameters : isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))]; } function getParametersInScope(node) { - return isFunctionLike(node) || isJSDocSignature(node) ? getExpandedParameters( - getSignatureFromDeclaration(node), - /*skipUnionExpanding*/ - true - )[0] : void 0; - } - function enterNewScope(context, declaration, expandedParams, typeParameters) { - let cleanup; - if (context.enclosingDeclaration && declaration && declaration !== context.enclosingDeclaration && !isInJSFile(declaration) && (some(expandedParams) || some(typeParameters))) { + return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).parameters : void 0; + } + function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) { + const cleanupContext = cloneNodeBuilderContext(context); + let cleanupParams; + let cleanupTypeParams; + const oldEnclosingDecl = context.enclosingDeclaration; + const oldMapper = context.mapper; + if (mapper) { + context.mapper = mapper; + } + if (context.enclosingDeclaration && declaration) { let pushFakeScope2 = function(kind, addAll) { Debug.assert(context.enclosingDeclaration); let existingFakeScope; @@ -50745,40 +50534,45 @@ function createTypeChecker(host) { Debug.assertOptionalNode(existingFakeScope, isBlock); const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable(); let newLocals; + let oldLocals; addAll((name, symbol) => { - if (!locals.has(name)) { - newLocals = append(newLocals, name); - locals.set(name, symbol); + if (existingFakeScope) { + const oldSymbol = locals.get(name); + if (!oldSymbol) { + newLocals = append(newLocals, name); + } else { + oldLocals = append(oldLocals, { name, oldSymbol }); + } } + locals.set(name, symbol); }); - if (!newLocals) - return; - const oldCleanup = cleanup; - function undo() { - forEach(newLocals, (s) => locals.delete(s)); - oldCleanup == null ? void 0 : oldCleanup(); - } - if (existingFakeScope) { - cleanup = undo; - } else { - const fakeScope = parseNodeFactory.createBlock(emptyArray); + if (!existingFakeScope) { + const fakeScope = factory.createBlock(emptyArray); getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind; fakeScope.locals = locals; - const saveEnclosingDeclaration = context.enclosingDeclaration; - setParent(fakeScope, saveEnclosingDeclaration); + setParent(fakeScope, context.enclosingDeclaration); context.enclosingDeclaration = fakeScope; - cleanup = () => { - context.enclosingDeclaration = saveEnclosingDeclaration; - undo(); + } else { + return function undo() { + forEach(newLocals, (s) => locals.delete(s)); + forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol)); }; } }; var pushFakeScope = pushFakeScope2; - pushFakeScope2( + cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope2( "params", (add) => { - for (const param of expandedParams ?? emptyArray) { - if (!forEach(param.declarations, (d) => { + if (!expandedParams) return; + for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) { + const param = expandedParams[pIndex]; + const originalParam = originalParameters == null ? void 0 : originalParameters[pIndex]; + if (originalParameters && originalParam !== param) { + add(param.escapedName, unknownSymbol); + if (originalParam) { + add(originalParam.escapedName, unknownSymbol); + } + } else if (!forEach(param.declarations, (d) => { if (isParameter(d) && isBindingPattern(d.name)) { bindPattern(d.name); return true; @@ -50809,8 +50603,8 @@ function createTypeChecker(host) { } } ); - if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { - pushFakeScope2( + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && some(typeParameters)) { + cleanupTypeParams = pushFakeScope2( "typeParams", (add) => { for (const typeParam of typeParameters ?? emptyArray) { @@ -50820,8 +50614,14 @@ function createTypeChecker(host) { } ); } - return cleanup; } + return () => { + cleanupParams == null ? void 0 : cleanupParams(); + cleanupTypeParams == null ? void 0 : cleanupTypeParams(); + cleanupContext(); + context.enclosingDeclaration = oldEnclosingDecl; + context.mapper = oldMapper; + }; } function tryGetThisParameterDeclaration(signature, context) { if (signature.thisParameter) { @@ -50838,7 +50638,7 @@ function createTypeChecker(host) { "this", /*questionToken*/ void 0, - typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context) + typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context) ); } } @@ -50853,8 +50653,11 @@ function createTypeChecker(host) { context.flags = savedContextFlags; return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); } + function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) { + return typeNode && tryReuseExistingNonParameterTypeNode(context, typeNode, type) || typeToTypeNodeHelper(type, context); + } function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) { - const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function typePredicateToTypePredicateNodeHelper(typePredicate, context) { @@ -50929,8 +50732,7 @@ function createTypeChecker(host) { } } function trackComputedName(accessExpression, enclosingDeclaration, context) { - if (!context.tracker.canTrackSymbol) - return; + if (!context.tracker.canTrackSymbol) return; const firstIdentifier = getFirstIdentifier(accessExpression); const name = resolveName( firstIdentifier, @@ -51040,7 +50842,11 @@ function createTypeChecker(host) { if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) { return void 0; } - (context.typeParameterSymbolList || (context.typeParameterSymbolList = /* @__PURE__ */ new Set())).add(symbolId); + if (context.mustCreateTypeParameterSymbolList) { + context.mustCreateTypeParameterSymbolList = false; + context.typeParameterSymbolList = new Set(context.typeParameterSymbolList); + } + context.typeParameterSymbolList.add(symbolId); let typeParameterNodes; if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) { const parentSymbol = symbol; @@ -51243,8 +51049,7 @@ function createTypeChecker(host) { } } const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; if (index > stopper) { const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper); @@ -51272,7 +51077,7 @@ function createTypeChecker(host) { return false; } function typeParameterToName(type, context) { - var _a, _b; + var _a, _b, _c, _d; if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { const cached = context.typeParameterNames.get(getTypeId(type)); if (cached) { @@ -51289,11 +51094,15 @@ function createTypeChecker(host) { if (!(result.kind & 80 /* Identifier */)) { return factory.createIdentifier("(Missing type parameter)"); } + const decl = (_b = (_a = type.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0]; + if (decl && isTypeParameterDeclaration(decl)) { + result = setTextRange2(context, result, decl.name); + } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const rawtext = result.escapedText; - let i = ((_a = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _a.get(rawtext)) || 0; + let i = ((_c = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _c.get(rawtext)) || 0; let text = rawtext; - while (((_b = context.typeParameterNamesByText) == null ? void 0 : _b.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) { + while (((_d = context.typeParameterNamesByText) == null ? void 0 : _d.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) { i++; text = `${rawtext}_${i}`; } @@ -51302,9 +51111,15 @@ function createTypeChecker(host) { result = factory.createIdentifier(text); setIdentifierTypeArguments(result, typeArguments); } - (context.typeParameterNamesByTextNextNameCount || (context.typeParameterNamesByTextNextNameCount = /* @__PURE__ */ new Map())).set(rawtext, i); - (context.typeParameterNames || (context.typeParameterNames = /* @__PURE__ */ new Map())).set(getTypeId(type), result); - (context.typeParameterNamesByText || (context.typeParameterNamesByText = /* @__PURE__ */ new Set())).add(text); + if (context.mustCreateTypeParametersNamesLookups) { + context.mustCreateTypeParametersNamesLookups = false; + context.typeParameterNames = new Map(context.typeParameterNames); + context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount); + context.typeParameterNamesByText = new Set(context.typeParameterNamesByText); + } + context.typeParameterNamesByTextNextNameCount.set(rawtext, i); + context.typeParameterNames.set(getTypeId(type), result); + context.typeParameterNamesByText.add(text); } return result; } @@ -51325,8 +51140,7 @@ function createTypeChecker(host) { context.flags ^= 16777216 /* InInitialEntityName */; } const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier; } @@ -51350,8 +51164,7 @@ function createTypeChecker(host) { } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier; } else { @@ -51367,8 +51180,7 @@ function createTypeChecker(host) { } if (!expression) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; expression = identifier; } @@ -51429,35 +51241,33 @@ function createTypeChecker(host) { } } function cloneNodeBuilderContext(context) { - const initial = { ...context }; - if (initial.typeParameterNames) { - initial.typeParameterNames = new Map(initial.typeParameterNames); - } - if (initial.typeParameterNamesByText) { - initial.typeParameterNamesByText = new Set(initial.typeParameterNamesByText); - } - if (initial.typeParameterSymbolList) { - initial.typeParameterSymbolList = new Set(initial.typeParameterSymbolList); - } - if (initial.typeParameterNamesByTextNextNameCount) { - initial.typeParameterNamesByTextNextNameCount = new Map(initial.typeParameterNamesByTextNextNameCount); - } - initial.tracker = new SymbolTrackerImpl(initial, initial.tracker.inner, initial.tracker.moduleResolverHost); - return initial; + const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList; + const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups; + context.mustCreateTypeParameterSymbolList = true; + context.mustCreateTypeParametersNamesLookups = true; + const oldTypeParameterNames = context.typeParameterNames; + const oldTypeParameterNamesByText = context.typeParameterNamesByText; + const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount; + const oldTypeParameterSymbolList = context.typeParameterSymbolList; + return () => { + context.typeParameterNames = oldTypeParameterNames; + context.typeParameterNamesByText = oldTypeParameterNamesByText; + context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount; + context.typeParameterSymbolList = oldTypeParameterSymbolList; + context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList; + context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups; + }; } function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration))); } function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) { - if (!(getObjectFlags(type) & 4 /* Reference */)) - return true; - if (!isTypeReferenceNode(existing)) - return true; + if (!(getObjectFlags(type) & 4 /* Reference */)) return true; + if (!isTypeReferenceNode(existing)) return true; void getTypeFromTypeReference(existing); const symbol = getNodeLinks(existing).resolvedSymbol; const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol); - if (!existingTarget || existingTarget !== type.target) - return true; + if (!existingTarget || existingTarget !== type.target) return true; return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters); } function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) { @@ -51470,31 +51280,32 @@ function createTypeChecker(host) { var _a; const addUndefined = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration); const enclosingDeclaration = context.enclosingDeclaration; - if (!isErrorType(type) && enclosingDeclaration) { - const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol, getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration)); + const oldFlags = context.flags; + if (declaration && hasInferredType(declaration) && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { + syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, context); + } + context.flags |= -2147483648 /* NoSyntacticPrinter */; + if (enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */)) { + const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol); if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) { const existing = getNonlocalEffectiveTypeAnnotationNode(declWithExistingAnnotation); - const result2 = tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); + const result2 = !isTypePredicateNode(existing) && tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); if (result2) { + context.flags = oldFlags; return result2; } } } - const oldFlags = context.flags; if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) { context.flags |= 1048576 /* AllowUniqueESSymbolType */; } const decl = declaration ?? symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); const expr = decl && isDeclarationWithPossibleInnerTypeNodeReuse(decl) ? getPossibleTypeNodeReuseExpression(decl) : void 0; - if (decl && hasInferredType(decl) && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { - syntacticNodeBuilder.serializeTypeOfDeclaration(decl, context); - } - context.flags |= -2147483648 /* NoSyntacticPrinter */; const result = expressionOrTypeToTypeNode(context, expr, type, addUndefined); context.flags = oldFlags; return result; } - function typeNodeIsEquivalentToType(typeNode, annotatedDeclaration, type, typeFromTypeNode = getTypeFromTypeNode(typeNode)) { + function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) { if (typeFromTypeNode === type) { return true; } @@ -51506,8 +51317,7 @@ function createTypeChecker(host) { function serializeReturnTypeForSignature(context, signature) { const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; const flags = context.flags; - if (suppressAny) - context.flags &= ~256 /* SuppressAnyReturnType */; + if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; let returnTypeNode; const returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { @@ -51525,13 +51335,10 @@ function createTypeChecker(host) { function serializeReturnTypeForSignatureWorker(context, signature) { const typePredicate = getTypePredicateOfSignature(signature); const type = getReturnTypeOfSignature(signature); - if (!isErrorType(type) && context.enclosingDeclaration) { + if (context.enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */) && signature.declaration && !nodeIsSynthesized(signature.declaration)) { const annotation = signature.declaration && getNonlocalEffectiveReturnTypeAnnotationNode(signature.declaration); - const enclosingDeclarationIgnoringFakeScope = getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); - if (!!findAncestor(annotation, (n) => n === enclosingDeclarationIgnoringFakeScope) && annotation) { - const annotated = getTypeFromTypeNode(annotation); - const thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; - const result = tryReuseExistingNonParameterTypeNode(context, annotation, type, signature.declaration, thisInstantiated); + if (annotation && getTypeFromTypeNode2(context, annotation) === type) { + const result = tryReuseExistingTypeNodeHelper(context, annotation); if (result) { return result; } @@ -51580,13 +51387,37 @@ function createTypeChecker(host) { /*dontResolveAlias*/ true ); + if (context.enclosingDeclaration && !(sym && sym.flags & 262144 /* TypeParameter */)) { + sym = getExportSymbolOfValueSymbolIfExported(sym); + const symAtLocation = resolveEntityName( + leftmost, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + context.enclosingDeclaration + ); + if ( + // Check for unusable parameters symbols + symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node + symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it shoudl point to the same reference + symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym) + ) { + if (symAtLocation !== unknownSymbol) { + context.tracker.reportInferenceFallback(node); + } + introducesError = true; + return { introducesError, node, sym }; + } + } if (sym) { if (sym.flags & 1 /* FunctionScopedVariable */ && sym.valueDeclaration) { - if (isPartOfParameterDeclaration(sym.valueDeclaration)) { + if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) { return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; } } - if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the curent context if they are are resolvable + if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable !isDeclarationName(node) && isSymbolAccessible( sym, context.enclosingDeclaration, @@ -51594,6 +51425,7 @@ function createTypeChecker(host) { /*shouldComputeAliasesToMakeVisible*/ false ).accessibility !== 0 /* Accessible */) { + context.tracker.reportInferenceFallback(node); introducesError = true; } else { context.tracker.trackSymbol(sym, context.enclosingDeclaration, meaning); @@ -51620,33 +51452,209 @@ function createTypeChecker(host) { return updated; } } + function serializeTypeName(context, node, isTypeOf, typeArguments) { + const meaning = isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const symbol = resolveEntityName( + node, + meaning, + /*ignoreErrors*/ + true + ); + if (!symbol) return void 0; + const resolvedSymbol = symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol; + if (isSymbolAccessible( + symbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */) return void 0; + return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments); + } + function canReuseTypeNode(context, existing) { + if (isInJSFile(existing)) { + if (isLiteralImportTypeNode(existing)) { + void getTypeFromImportTypeNode(existing); + const nodeSymbol = getNodeLinks(existing).resolvedSymbol; + return !nodeSymbol || !// The import type resolved using jsdoc fallback logic + (!existing.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic + !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol)))); + } + } + if (isThisTypeNode(existing)) { + if (context.mapper === void 0) return true; + const type = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + ); + return !!type; + } + if (isTypeReferenceNode(existing)) { + if (isConstTypeReference(existing)) return false; + const type = getTypeFromTypeReference(existing); + const symbol = getNodeLinks(existing).resolvedSymbol; + if (!symbol) return false; + if (symbol.flags & 262144 /* TypeParameter */) { + const type2 = getDeclaredTypeOfSymbol(symbol); + if (context.mapper && getMappedType(type2, context.mapper) !== type2) { + return false; + } + } + if (isInJSDoc(existing)) { + return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && symbol.flags & 788968 /* Type */; + } + } + if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) { + const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); + return !!findAncestor(existing, (n) => n === effectiveEnclosingContext); + } + return true; + } + function serializeExistingTypeNode(context, typeNode) { + const type = getTypeFromTypeNode2(context, typeNode); + return typeToTypeNodeHelper(type, context); + } function tryReuseExistingTypeNodeHelper(context, existing) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } let hadError = false; + const { finalizeBoundary, startRecoveryScope } = createRecoveryBoundary(); const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode); - if (hadError) { + if (!finalizeBoundary()) { return void 0; } + context.approximateLength += existing.end - existing.pos; return transformed; function visitExistingNodeTreeSymbols(node) { + if (hadError) return node; + const recover = startRecoveryScope(); const onExitNewScope = isNewScopeNode(node) ? onEnterNewScope(node) : void 0; const result = visitExistingNodeTreeSymbolsWorker(node); onExitNewScope == null ? void 0 : onExitNewScope(); - return result === node ? setTextRange2(context, factory.cloneNode(result), node) : result; + if (hadError) { + if (isTypeNode(node) && !isTypePredicateNode(node)) { + recover(); + return serializeExistingTypeNode(context, node); + } + return node; + } + return result ? setTextRange2(context, result, node) : void 0; + } + function createRecoveryBoundary() { + let unreportedErrors; + const oldTracker = context.tracker; + const oldTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = []; + const oldEncounteredError = context.encounteredError; + context.tracker = new SymbolTrackerImpl(context, { + ...oldTracker.inner, + reportCyclicStructureError() { + markError(() => oldTracker.reportCyclicStructureError()); + }, + reportInaccessibleThisError() { + markError(() => oldTracker.reportInaccessibleThisError()); + }, + reportInaccessibleUniqueSymbolError() { + markError(() => oldTracker.reportInaccessibleUniqueSymbolError()); + }, + reportLikelyUnsafeImportRequiredError(specifier) { + markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier)); + }, + reportNonSerializableProperty(name) { + markError(() => oldTracker.reportNonSerializableProperty(name)); + }, + trackSymbol(sym, decl, meaning) { + const accessibility = isSymbolAccessible( + sym, + decl, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ); + if (accessibility.accessibility !== 0 /* Accessible */) { + (context.trackedSymbols ?? (context.trackedSymbols = [])).push([sym, decl, meaning]); + return true; + } + return false; + }, + moduleResolverHost: context.tracker.moduleResolverHost + }, context.tracker.moduleResolverHost); + return { + startRecoveryScope: startRecoveryScope2, + finalizeBoundary: finalizeBoundary2 + }; + function markError(unreportedError) { + hadError = true; + (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError); + } + function startRecoveryScope2() { + var _a; + const initialTrackedSymbolsTop = ((_a = context.trackedSymbols) == null ? void 0 : _a.length) ?? 0; + const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0; + return () => { + hadError = false; + if (context.trackedSymbols) { + context.trackedSymbols.length = initialTrackedSymbolsTop; + } + if (unreportedErrors) { + unreportedErrors.length = unreportedErrorsTop; + } + }; + } + function finalizeBoundary2() { + context.tracker = oldTracker; + const newTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = oldTrackedSymbols; + context.encounteredError = oldEncounteredError; + unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn()); + if (hadError) { + return false; + } + newTrackedSymbols == null ? void 0 : newTrackedSymbols.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); + return true; + } } function onEnterNewScope(node) { - const oldContex = context; - context = cloneNodeBuilderContext(context); - const cleanup = enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node)); - return onExitNewScope; - function onExitNewScope() { - cleanup == null ? void 0 : cleanup(); - context = oldContex; + return enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node)); + } + function tryVisitTypeReference(node) { + if (canReuseTypeNode(context, node)) { + const { introducesError, node: newName } = trackExistingEntityName(node.typeName, context); + const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode); + if (!introducesError) { + const updated = factory.updateTypeReferenceNode( + node, + newName, + typeArguments + ); + return setTextRange2(context, updated, node); + } else { + const serializedName = serializeTypeName( + context, + node.typeName, + /*isTypeOf*/ + false, + typeArguments + ); + if (serializedName) { + return setTextRange2(context, serializedName, node.typeName); + } + } } } function visitExistingNodeTreeSymbolsWorker(node) { + if (isJSDocTypeExpression(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode); + } if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) { return factory.createKeywordTypeNode(133 /* AnyKeyword */); } @@ -51668,8 +51676,8 @@ function createTypeChecker(host) { if (isJSDocTypeLiteral(node)) { return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { const name = isIdentifier(t.name) ? t.name : t.name.right; - const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText); - const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; + const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, node), name.escapedText); + const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode2(context, t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; return factory.createPropertySignature( /*modifiers*/ void 0, @@ -51710,7 +51718,7 @@ function createTypeChecker(host) { /*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), + setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ @@ -51725,7 +51733,7 @@ function createTypeChecker(host) { /*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), + setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ @@ -51735,20 +51743,44 @@ function createTypeChecker(host) { ); } } - if (isTypeReferenceNode(node) && isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName( - node, - 788968 /* Type */, - /*ignoreErrors*/ - true - ))) { - return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); + if (isThisTypeNode(node)) { + if (canReuseTypeNode(context, node)) { + return node; + } + hadError = true; + return node; + } + if (isTypeParameterDeclaration(node)) { + return factory.updateTypeParameterDeclaration( + node, + node.modifiers, + setTextRange2(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node), + visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode), + visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + if (isIndexedAccessTypeNode(node) && isTypeReferenceNode(node.objectType)) { + const objectType = tryVisitTypeReference(node.objectType); + if (!objectType) { + hadError = true; + return node; + } + return factory.updateIndexedAccessTypeNode(node, objectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTypeReferenceNode(node)) { + const result = tryVisitTypeReference(node); + if (result) { + return result; + } + hadError = true; + return node; } if (isLiteralImportTypeNode(node)) { const nodeSymbol = getNodeLinks(node).resolvedSymbol; if (isInJSDoc(node) && nodeSymbol && // The import type resolved using jsdoc fallback logic (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic !(length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { - return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); + return setTextRange2(context, typeToTypeNodeHelper(getTypeFromTypeNode2(context, node), context), node); } return factory.updateImportTypeNode( node, @@ -51760,15 +51792,12 @@ function createTypeChecker(host) { ); } if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !isLateBindableName(node.name)) { - return void 0; + if (!(context.flags & 1 /* AllowUnresolvedNames */ && hasDynamicName(node) && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */)) { + return void 0; + } } if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) { - let visited = visitEachChild( - node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 - ); + let visited = visitEachChild2(node, visitExistingNodeTreeSymbols); if (visited === node) { visited = setTextRange2(context, factory.cloneNode(node), node); } @@ -51778,21 +51807,58 @@ function createTypeChecker(host) { } return visited; } - if (isEntityName(node) || isEntityNameExpression(node)) { - if (isDeclarationName(node)) { + if (isTypeQueryNode(node)) { + const { introducesError, node: exprName } = trackExistingEntityName(node.exprName, context); + if (introducesError) { + const serializedName = serializeTypeName( + context, + node.exprName, + /*isTypeOf*/ + true + ); + if (serializedName) { + return setTextRange2(context, serializedName, node.exprName); + } + hadError = true; return node; } - const { introducesError, node: result } = trackExistingEntityName(node, context); - hadError = hadError || introducesError; - return result; - } - if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { - const visited = visitEachChild( + return factory.updateTypeQueryNode( node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 + exprName, + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode) ); + } + if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) { + const { node: result, introducesError } = trackExistingEntityName(node.expression, context); + if (!introducesError) { + return factory.updateComputedPropertyName(node, result); + } else { + const type = getWidenedType(getRegularTypeOfExpression(node.expression)); + const computedPropertyNameType = typeToTypeNodeHelper(type, context); + Debug.assertNode(computedPropertyNameType, isLiteralTypeNode); + const literal = computedPropertyNameType.literal; + if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(compilerOptions))) { + return factory.createIdentifier(literal.text); + } + if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) { + return literal; + } + return factory.updateComputedPropertyName(node, literal); + } + } + if (isTypePredicateNode(node)) { + let parameterName; + if (isIdentifier(node.parameterName)) { + const { node: result, introducesError } = trackExistingEntityName(node.parameterName, context); + hadError = hadError || introducesError; + parameterName = result; + } else { + parameterName = node.parameterName; + } + return factory.updateTypePredicateNode(node, node.assertsModifier, parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { + const visited = visitEachChild2(node, visitExistingNodeTreeSymbols); const clone = setTextRange2(context, visited === node ? factory.cloneNode(node) : visited, node); const flags = getEmitFlags(clone); setEmitFlags(clone, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */)); @@ -51818,12 +51884,46 @@ function createTypeChecker(host) { falseType2 ); } - return visitEachChild( - node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 - ); + if (isTypeOperatorNode(node)) { + if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) { + if (!canReuseTypeNode(context, node)) { + hadError = true; + return node; + } + } else if (node.operator === 143 /* KeyOfKeyword */) { + if (isTypeReferenceNode(node.type)) { + const type = tryVisitTypeReference(node.type); + if (!type) { + hadError = true; + return node; + } + return factory.updateTypeOperatorNode(node, type); + } + } + } + return visitEachChild2(node, visitExistingNodeTreeSymbols); + function visitEachChild2(node2, visitor) { + const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2); + return visitEachChild( + node2, + visitor, + /*context*/ + void 0, + nonlocalNode ? visitNodesWithoutCopyingPositions : void 0 + ); + } + function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) { + let result = visitNodes2(nodes, visitor, test, start, count); + if (result) { + if (result.pos !== -1 || result.end !== -1) { + if (result === nodes) { + result = factory.createNodeArray(nodes, nodes.hasTrailingComma); + } + setTextRangePosEnd(result, -1, -1); + } + } + return result; + } function getEffectiveDotDotDotForParameter(p) { return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); } @@ -51832,13 +51932,39 @@ function createTypeChecker(host) { } function rewriteModuleSpecifier(parent, lit) { if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) { - const targetFile = getExternalModuleFileFromDeclaration(parent); - if (targetFile) { - const newName = getSpecifierForModuleSymbol(targetFile.symbol, context); - if (newName !== lit.text) { - return setOriginalNode(factory.createStringLiteral(newName), lit); + let name = lit.text; + const nodeSymbol = getNodeLinks(node).resolvedSymbol; + const meaning = parent.isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const parentSymbol = nodeSymbol && isSymbolAccessible( + nodeSymbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility === 0 /* Accessible */ && lookupSymbolChain( + nodeSymbol, + context, + meaning, + /*yieldModuleSymbol*/ + true + )[0]; + if (parentSymbol && parentSymbol.flags & 1536 /* Module */) { + name = getSpecifierForModuleSymbol(parentSymbol, context); + } else { + const targetFile = getExternalModuleFileFromDeclaration(parent); + if (targetFile) { + name = getSpecifierForModuleSymbol(targetFile.symbol, context); } } + if (name.includes("/node_modules/")) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(name); + } + } + if (name !== lit.text) { + return setOriginalNode(factory.createStringLiteral(name), lit); + } } return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral); } @@ -51874,8 +52000,7 @@ function createTypeChecker(host) { ...oldcontext.tracker.inner, trackSymbol: (sym, decl, meaning) => { var _a2, _b; - if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) - return false; + if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false; const accessibleResult = isSymbolAccessible( sym, decl, @@ -52085,6 +52210,7 @@ function createTypeChecker(host) { } } function serializeSymbol(symbol, isPrivate, propertyAsAlias) { + void getPropertiesOfType(getTypeOfSymbol(symbol)); const visitedSym = getMergedSymbol(symbol); if (visitedSymbols.has(getSymbolId(visitedSym))) { return; @@ -52092,19 +52218,9 @@ function createTypeChecker(host) { visitedSymbols.add(getSymbolId(visitedSym)); const skipMembershipCheck = !isPrivate; if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) { - const oldContext = context; - context = cloneNodeBuilderContext(context); + const scopeCleanup = cloneNodeBuilderContext(context); serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); - if (context.reportedDiagnostic) { - oldcontext.reportedDiagnostic = context.reportedDiagnostic; - } - if (context.trackedSymbols) { - if (!oldContext.trackedSymbols) - oldContext.trackedSymbols = context.trackedSymbols; - else - Debug.assert(context.trackedSymbols === oldContext.trackedSymbols); - } - context = oldContext; + scopeCleanup(); } } function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) { @@ -52247,8 +52363,7 @@ function createTypeChecker(host) { if (symbol.declarations) { for (const node of symbol.declarations) { const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; + if (!resolvedModule) continue; addResult(factory.createExportDeclaration( /*modifiers*/ void 0, @@ -52288,8 +52403,7 @@ function createTypeChecker(host) { } } function includePrivateSymbol(symbol) { - if (some(symbol.declarations, isPartOfParameterDeclaration)) - return; + if (some(symbol.declarations, isPartOfParameterDeclaration)) return; Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]); getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol); const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)); @@ -52567,7 +52681,7 @@ function createTypeChecker(host) { } return cleanup(factory.createExpressionWithTypeArguments( expr, - map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode(a)) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)) + map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode2(context, a)) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context)) )); function cleanup(result2) { context.enclosingDeclaration = oldEnclosing; @@ -52680,8 +52794,7 @@ function createTypeChecker(host) { function serializeAsAlias(symbol, localName, modifierFlags) { var _a2, _b, _c, _d, _e, _f; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); const target = getMergedSymbol(getTargetOfAliasDeclaration( node, /*dontRecursivelyResolve*/ @@ -53418,10 +53531,8 @@ function createTypeChecker(host) { result.push(t); } } - if (flags & 65536 /* Null */) - result.push(nullType); - if (flags & 32768 /* Undefined */) - result.push(undefinedType); + if (flags & 65536 /* Null */) result.push(nullType); + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } function visibilityToString(flags) { @@ -53676,8 +53787,6 @@ function createTypeChecker(host) { switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; - case 5 /* EnumTagType */: - return !!getNodeLinks(target).resolvedEnumType; case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -53686,13 +53795,13 @@ function createTypeChecker(host) { return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; - case 6 /* ResolvedTypeArguments */: + case 5 /* ResolvedTypeArguments */: return !!target.resolvedTypeArguments; - case 7 /* ResolvedBaseTypes */: + case 6 /* ResolvedBaseTypes */: return !!target.baseTypesResolved; - case 8 /* WriteType */: + case 7 /* WriteType */: return !!getSymbolLinks(target).writeType; - case 9 /* ParameterInitializerContainsUndefined */: + case 8 /* ParameterInitializerContainsUndefined */: return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0; } return Debug.assertNever(propertyName); @@ -54004,8 +54113,7 @@ function createTypeChecker(host) { } } const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration); - if (parameterTypeOfTypeTag) - return parameterTypeOfTypeTag; + if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag; const type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality( @@ -54572,12 +54680,9 @@ function createTypeChecker(host) { result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; result.parent = symbol; result.links.target = fileSymbol; - if (fileSymbol.valueDeclaration) - result.valueDeclaration = fileSymbol.valueDeclaration; - if (fileSymbol.members) - result.members = new Map(fileSymbol.members); - if (fileSymbol.exports) - result.exports = new Map(fileSymbol.exports); + if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) result.members = new Map(fileSymbol.members); + if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports); const members = createSymbolTable(); members.set("exports", result); return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); @@ -54708,14 +54813,14 @@ function createTypeChecker(host) { } type = anyType; } - links.type = type; + links.type ?? (links.type = type); } return links.type; } function getWriteTypeOfAccessors(symbol) { const links = getSymbolLinks(symbol); if (!links.writeType) { - if (!pushTypeResolution(symbol, 8 /* WriteType */)) { + if (!pushTypeResolution(symbol, 7 /* WriteType */)) { return errorType; } const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); @@ -54726,7 +54831,7 @@ function createTypeChecker(host) { } writeType = anyType; } - links.writeType = writeType || getTypeOfAccessors(symbol); + links.writeType ?? (links.writeType = writeType || getTypeOfAccessors(symbol)); } return links.writeType; } @@ -54803,10 +54908,10 @@ function createTypeChecker(host) { true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type ?? (links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType); if (!popTypeResolution()) { reportCircularityError(exportSymbol ?? symbol); - return links.type = errorType; + return links.type ?? (links.type = errorType); } } return links.type; @@ -55072,7 +55177,7 @@ function createTypeChecker(host) { } if (!popTypeResolution()) { error(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = errorType; + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { const err = error(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); @@ -55089,9 +55194,9 @@ function createTypeChecker(host) { addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); } } - return type.resolvedBaseConstructorType = errorType; + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); } - type.resolvedBaseConstructorType = baseConstructorType; + type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = baseConstructorType); } return type.resolvedBaseConstructorType; } @@ -55100,8 +55205,7 @@ function createTypeChecker(host) { if (type.symbol.declarations) { for (const declaration of type.symbol.declarations) { const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; + if (!implementsTypeNodes) continue; for (const node of implementsTypeNodes) { const implementsType = getTypeFromTypeNode(node); if (!isErrorType(implementsType)) { @@ -55126,7 +55230,7 @@ function createTypeChecker(host) { } function getBaseTypes(type) { if (!type.baseTypesResolved) { - if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) { + if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) { if (type.objectFlags & 8 /* Tuple */) { type.resolvedBaseTypes = [getTupleBaseType(type)]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -55332,7 +55436,7 @@ function createTypeChecker(host) { error(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } - links.declaredType = type; + links.declaredType ?? (links.declaredType = type); } return links.declaredType; } @@ -55562,8 +55666,7 @@ function createTypeChecker(host) { const memberName = getPropertyNameFromType(type); const symbolFlags = decl.symbol.flags; let lateSymbol = lateSymbols.get(memberName); - if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); + if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); const earlySymbol = earlySymbols && earlySymbols.get(memberName); if (!(parent.flags & 32 /* Class */) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) { const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; @@ -55624,16 +55727,12 @@ function createTypeChecker(host) { resolved = original; continue; } - if (!original) - continue; + if (!original) continue; original.forEach((s, name) => { const existing = resolved.get(name); - if (!existing) - resolved.set(name, s); - else if (existing === s) - return; - else - resolved.set(name, mergeSymbol(existing, s)); + if (!existing) resolved.set(name, s); + else if (existing === s) return; + else resolved.set(name, mergeSymbol(existing, s)); }); } } @@ -55928,8 +56027,7 @@ function createTypeChecker(host) { let result; let indexWithLengthOverOne; for (let i = 0; i < signatureLists.length; i++) { - if (signatureLists[i].length === 0) - return emptyArray; + if (signatureLists[i].length === 0) return emptyArray; if (signatureLists[i].length > 1) { indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1; } @@ -55990,10 +56088,8 @@ function createTypeChecker(host) { for (let i = 0; i < sourceParams.length; i++) { const source = sourceParams[i]; const target = targetParams[i]; - if (source === target) - continue; - if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) - return false; + if (source === target) continue; + if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false; } return true; } @@ -56450,6 +56546,7 @@ function createTypeChecker(host) { } } function getTypeOfMappedSymbol(symbol) { + var _a; if (!symbol.links.type) { const mappedType = symbol.links.mappedType; if (!pushTypeResolution(symbol, 0 /* Type */)) { @@ -56468,7 +56565,7 @@ function createTypeChecker(host) { error(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); type = errorType; } - symbol.links.type = type; + (_a = symbol.links).type ?? (_a.type = type); } return symbol.links.type; } @@ -56649,8 +56746,7 @@ function createTypeChecker(host) { for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) { if (!props.has(escapedName)) { const prop = createUnionOrIntersectionProperty(unionType, escapedName); - if (prop) - props.set(escapedName, prop); + if (prop) props.set(escapedName, prop); } } } @@ -56767,7 +56863,7 @@ function createTypeChecker(host) { } } return getNormalizedType( - getIntersectionType(constraints), + getIntersectionType(constraints, 2 /* NoConstraintReduction */), /*writing*/ false ); @@ -56821,7 +56917,7 @@ function createTypeChecker(host) { } result = circularConstraintType; } - t.immediateBaseConstraint = result || noConstraintType; + t.immediateBaseConstraint ?? (t.immediateBaseConstraint = result || noConstraintType); } return t.immediateBaseConstraint; } @@ -56893,7 +56989,16 @@ function createTypeChecker(host) { } } function getApparentTypeOfIntersectionType(type, thisArgument) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( + if (type === thisArgument) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( + type, + thisArgument, + /*needApparentType*/ + true + )); + } + const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`; + return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument( type, thisArgument, /*needApparentType*/ @@ -57211,8 +57316,7 @@ function createTypeChecker(host) { if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } - if (skipObjectFunctionPropertyAugment) - return void 0; + if (skipObjectFunctionPropertyAugment) return void 0; const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0; if (functionType) { const symbol2 = getPropertyOfObjectType(functionType, name); @@ -57527,15 +57631,13 @@ function createTypeChecker(host) { return true; } function getSignatureOfTypeTag(node) { - if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) - return void 0; + if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0; const typeTag = getJSDocTypeTag(node); return (typeTag == null ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getParameterTypeOfTypeTag(func, parameter) { const signature = getSignatureOfTypeTag(func); - if (!signature) - return void 0; + if (!signature) return void 0; const pos = func.parameters.indexOf(parameter); return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); } @@ -57554,8 +57656,7 @@ function createTypeChecker(host) { } return links.containsArgumentsReference; function traverse(node) { - if (!node) - return false; + if (!node) return false; switch (node.kind) { case 80 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; @@ -57575,13 +57676,11 @@ function createTypeChecker(host) { } } function getSignaturesOfSymbol(symbol) { - if (!symbol || !symbol.declarations) - return emptyArray; + if (!symbol || !symbol.declarations) return emptyArray; const result = []; for (let i = 0; i < symbol.declarations.length; i++) { const decl = symbol.declarations[i]; - if (!isFunctionLike(decl)) - continue; + if (!isFunctionLike(decl)) continue; if (i > 0 && decl.body) { const previous = symbol.declarations[i - 1]; if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { @@ -57695,7 +57794,7 @@ function createTypeChecker(host) { } type = anyType; } - signature.resolvedReturnType = type; + signature.resolvedReturnType ?? (signature.resolvedReturnType = type); } return signature.resolvedReturnType; } @@ -58035,15 +58134,15 @@ function createTypeChecker(host) { function getTypeArguments(type) { var _a, _b; if (!type.resolvedTypeArguments) { - if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) { + if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) { return ((_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray; } const node = type.node; const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments); } else { - type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray; + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray); error( type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, @@ -58972,8 +59071,7 @@ function createTypeChecker(host) { lengthSymbol.links.type = numberType; } else { const literalTypes = []; - for (let i = minLength; i <= arity; i++) - literalTypes.push(getNumberLiteralType(i)); + for (let i = minLength; i <= arity; i++) literalTypes.push(getNumberLiteralType(i)); lengthSymbol.links.type = getUnionType(literalTypes); } properties.push(lengthSymbol); @@ -59050,8 +59148,7 @@ function createTypeChecker(host) { } } for (let i = 0; i < lastRequiredIndex; i++) { - if (expandedFlags[i] & 2 /* Optional */) - expandedFlags[i] = 1 /* Required */; + if (expandedFlags[i] & 2 /* Optional */) expandedFlags[i] = 1 /* Required */; } if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) { expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t)); @@ -59134,15 +59231,12 @@ function createTypeChecker(host) { const flags = type.flags; if (!(flags & 131072 /* Never */)) { includes |= flags & 473694207 /* IncludesMask */; - if (flags & 465829888 /* Instantiable */) - includes |= 33554432 /* IncludesInstantiable */; - if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) - includes |= 536870912 /* IncludesConstrainedTypeVariable */; - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (flags & 465829888 /* Instantiable */) includes |= 33554432 /* IncludesInstantiable */; + if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) includes |= 536870912 /* IncludesConstrainedTypeVariable */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) - includes |= 4194304 /* IncludesNonWideningType */; + if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { const len = typeSet.length; const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); @@ -59332,7 +59426,7 @@ function createTypeChecker(host) { const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType : unknownType; } if (includes & 32768 /* Undefined */) { if (typeSet.length >= 2 && typeSet[0] === undefinedType && typeSet[1] === missingType) { @@ -59457,8 +59551,8 @@ function createTypeChecker(host) { } } else { if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; } else if (strictNullChecks || !(flags & 98304 /* Nullable */)) { if (type === missingType) { includes |= 262144 /* IncludesMissingType */; @@ -59509,8 +59603,7 @@ function createTypeChecker(host) { while (i > 0) { i--; const t = types[i]; - if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */))) - continue; + if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */))) continue; for (const t2 of literals) { if (isTypeSubtypeOf(t2, t)) { orderedRemoveItemAt(types, i); @@ -59572,7 +59665,7 @@ function createTypeChecker(host) { result.aliasTypeArguments = aliasTypeArguments; return result; } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { + function getIntersectionType(types, flags = 0 /* None */, aliasSymbol, aliasTypeArguments) { const typeMembershipMap = /* @__PURE__ */ new Map(); const includes = addTypesToIntersection(typeMembershipMap, 0, types); const typeSet = arrayFrom(typeMembershipMap.values()); @@ -59587,14 +59680,13 @@ function createTypeChecker(host) { return neverType; } if (includes & 1 /* Any */) { - return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 16777216 /* IncludesEmptyObject */ ? neverType : includes & 32768 /* Undefined */ ? undefinedType : nullType; } if (includes & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || includes & 16384 /* Void */ && includes & 32768 /* Undefined */ || includes & 16777216 /* IncludesEmptyObject */ && includes & 470302716 /* DefinitelyNonNullable */) { - if (!noSupertypeReduction) - removeRedundantSupertypes(typeSet, includes); + if (!(flags & 1 /* NoSupertypeReduction */)) removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -59605,7 +59697,7 @@ function createTypeChecker(host) { if (typeSet.length === 1) { return typeSet[0]; } - if (typeSet.length === 2) { + if (typeSet.length === 2 && !(flags & 2 /* NoConstraintReduction */)) { const typeVarIndex = typeSet[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; const typeVariable = typeSet[typeVarIndex]; const primitiveType = typeSet[1 - typeVarIndex]; @@ -59624,27 +59716,27 @@ function createTypeChecker(host) { } } } - const id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); + const id = getTypeListId(typeSet) + (flags & 2 /* NoConstraintReduction */ ? "*" : getAliasId(aliasSymbol, aliasTypeArguments)); let result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { if (intersectUnionsOfPrimitiveTypes(typeSet)) { - result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + result = getIntersectionType(typeSet, flags, aliasSymbol, aliasTypeArguments); } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) { const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType; removeFromEach(typeSet, 32768 /* Undefined */); - result = getUnionType([getIntersectionType(typeSet), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + result = getUnionType([getIntersectionType(typeSet, flags), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { removeFromEach(typeSet, 65536 /* Null */); - result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + result = getUnionType([getIntersectionType(typeSet, flags), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); } else if (typeSet.length >= 4) { const middle = Math.floor(typeSet.length / 2); - result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle)), getIntersectionType(typeSet.slice(middle))], aliasSymbol, aliasTypeArguments); + result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle), flags), getIntersectionType(typeSet.slice(middle), flags)], flags, aliasSymbol, aliasTypeArguments); } else { if (!checkCrossProductUnion(typeSet)) { return errorType; } - const constituents = getCrossProductIntersections(typeSet); + const constituents = getCrossProductIntersections(typeSet, flags); const origin = some(constituents, (t) => !!(t.flags & 2097152 /* Intersection */)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : void 0; result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin); } @@ -59668,7 +59760,7 @@ function createTypeChecker(host) { } return true; } - function getCrossProductIntersections(types) { + function getCrossProductIntersections(types, flags) { const count = getCrossProductUnionSize(types); const intersections = []; for (let i = 0; i < count; i++) { @@ -59682,9 +59774,8 @@ function createTypeChecker(host) { n = Math.floor(n / length2); } } - const t = getIntersectionType(constituents); - if (!(t.flags & 131072 /* Never */)) - intersections.push(t); + const t = getIntersectionType(constituents, flags); + if (!(t.flags & 131072 /* Never */)) intersections.push(t); } return intersections; } @@ -59702,7 +59793,7 @@ function createTypeChecker(host) { const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1; const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType; const noSupertypeReduction = !!(t.flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */) || t.flags & 134217728 /* TemplateLiteral */ && isPatternLiteralType(t)); - links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); + links.resolvedType = getIntersectionType(types, noSupertypeReduction ? 1 /* NoSupertypeReduction */ : 0, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -59850,7 +59941,6 @@ function createTypeChecker(host) { return links.resolvedType; } function getTemplateLiteralType(texts, types) { - var _a, _b; const unionIndex = findIndex(types, (t) => !!(t.flags & (131072 /* Never */ | 1048576 /* Union */))); if (unionIndex >= 0) { return checkCrossProductUnion(types) ? mapType(types[unionIndex], (t) => getTemplateLiteralType(texts, replaceElement(types, unionIndex, t))) : errorType; @@ -59858,9 +59948,6 @@ function createTypeChecker(host) { if (contains(types, wildcardType)) { return wildcardType; } - if (texts.length === 2 && texts[0] === "" && texts[1] === "" && !(types[0].flags & 2944 /* Literal */) && !((_b = (_a = types[0].symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d) => d.parent.kind === 195 /* InferType */)) && isTypeAssignableTo(types[0], stringType)) { - return types[0]; - } const newTypes = []; const newTexts = []; let text = texts[0]; @@ -59893,8 +59980,7 @@ function createTypeChecker(host) { text += texts2[i + 1]; } else if (t.flags & 134217728 /* TemplateLiteral */) { text += t.texts[0]; - if (!addSpans(t.texts, t.types)) - return false; + if (!addSpans(t.texts, t.types)) return false; text += texts2[i + 1]; } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { newTypes.push(t); @@ -60362,8 +60448,7 @@ function createTypeChecker(host) { if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { indexType = stringType; } - if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) - accessFlags |= 1 /* IncludeUndefined */; + if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; @@ -60393,7 +60478,7 @@ function createTypeChecker(host) { if (wasMissingProp) { return void 0; } - return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments); + return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, 0 /* None */, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments); } return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* ReportDeprecated */); } @@ -61517,7 +61602,7 @@ function createTypeChecker(host) { } const newAliasSymbol = aliasSymbol || type.aliasSymbol; const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); - return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, 0 /* None */, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -61715,8 +61800,7 @@ function createTypeChecker(host) { ); } function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) { - if (isTypeRelatedTo(source, target, relation)) - return true; + if (isTypeRelatedTo(source, target, relation)) return true; if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer); } @@ -61726,8 +61810,7 @@ function createTypeChecker(host) { return !!(type.flags & 16777216 /* Conditional */ || type.flags & 2097152 /* Intersection */ && some(type.types, isOrHasGenericConditional)); } function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) { - if (!node || isOrHasGenericConditional(target)) - return false; + if (!node || isOrHasGenericConditional(target)) return false; if (!checkTypeRelatedTo( source, target, @@ -61899,11 +61982,9 @@ function createTypeChecker(host) { for (const value of iterator) { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = value; let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType); - if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) - continue; + if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; + if (!sourcePropType) continue; const propName = getPropertyNameFromIndex( nameType, /*accessNode*/ @@ -61994,11 +62075,9 @@ function createTypeChecker(host) { if (targetIndexedPropType && !(targetIndexedPropType.flags & 8388608 /* IndexedAccess */)) { targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType; } - if (!targetPropType) - continue; + if (!targetPropType) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; + if (!sourcePropType) continue; const propName = getPropertyNameFromIndex( nameType, /*accessNode*/ @@ -62045,17 +62124,14 @@ function createTypeChecker(host) { return reportedError; } function* generateJsxAttributes(node) { - if (!length(node.properties)) - return; + if (!length(node.properties)) return; for (const prop of node.properties) { - if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) - continue; + if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue; yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) }; } } function* generateJsxChildren(node, getInvalidTextDiagnostic) { - if (!length(node.children)) - return; + if (!length(node.children)) return; let memberOffset = 0; for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; @@ -62175,22 +62251,18 @@ function createTypeChecker(host) { } function* generateLimitedTupleElements(node, target) { const len = length(node.elements); - if (!len) - return; + if (!len) return; for (let i = 0; i < len; i++) { - if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) - continue; + if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) continue; const elem = node.elements[i]; - if (isOmittedExpression(elem)) - continue; + if (isOmittedExpression(elem)) continue; const nameType = getNumberLiteralType(i); const checkNode = getEffectiveCheckNode(elem); yield { errorNode: checkNode, innerExpression: checkNode, nameType }; } } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) - return false; + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -62213,11 +62285,9 @@ function createTypeChecker(host) { return false; } function* generateObjectLiteralElements(node) { - if (!length(node.properties)) - return; + if (!length(node.properties)) return; for (const prop of node.properties) { - if (isSpreadAssignment(prop)) - continue; + if (isSpreadAssignment(prop)) continue; const type = getLiteralTypeFromProperty(getSymbolOfDeclaration(prop), 8576 /* StringOrNumberLiteralOrUnique */); if (!type || type.flags & 131072 /* Never */) { continue; @@ -62238,8 +62308,7 @@ function createTypeChecker(host) { } } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) - return false; + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { @@ -62330,7 +62399,7 @@ function createTypeChecker(host) { for (let i = 0; i < paramCount; i++) { const sourceType = i === restIndex ? getRestOrAnyTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i); const targetType = i === restIndex ? getRestOrAnyTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i); - if (sourceType && targetType) { + if (sourceType && targetType && (sourceType !== targetType || checkMode & 8 /* StrictArity */)) { const sourceSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(source, i) ? void 0 : getSingleCallSignature(getNonNullableType(sourceType)); const targetSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(target, i) ? void 0 : getSingleCallSignature(getNonNullableType(targetType)); const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */); @@ -62520,49 +62589,29 @@ function createTypeChecker(host) { function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { const s = source.flags; const t = target.flags; - if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) - return true; - if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) - return true; - if (t & 131072 /* Never */) - return false; - if (s & 402653316 /* StringLike */ && t & 4 /* String */) - return true; - if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) - return true; - if (s & 296 /* NumberLike */ && t & 8 /* Number */) - return true; - if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) - return true; - if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) - return true; - if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) - return true; - if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) - return true; - if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; + if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) return true; + if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) return true; + if (t & 131072 /* Never */) return false; + if (s & 402653316 /* StringLike */ && t & 4 /* String */) return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { - if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; } - if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) - return true; - if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) - return true; - if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) - return true; + if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; + if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1 /* Any */) - return true; - if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) - return true; - if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */ && source.value === target.value)) - return true; - if (isUnknownLikeUnionType(target)) - return true; + if (s & 1 /* Any */) return true; + if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; + if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */ && source.value === target.value)) return true; + if (isUnknownLikeUnionType(target)) return true; } return false; } @@ -62581,10 +62630,8 @@ function createTypeChecker(host) { return true; } } else if (!((source.flags | target.flags) & (3145728 /* UnionOrIntersection */ | 8388608 /* IndexedAccess */ | 16777216 /* Conditional */ | 33554432 /* Substitution */))) { - if (source.flags !== target.flags) - return false; - if (source.flags & 67358815 /* Singleton */) - return true; + if (source.flags !== target.flags) return false; + if (source.flags & 67358815 /* Singleton */) return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { const related = relation.get(getRelationKey( @@ -62616,8 +62663,7 @@ function createTypeChecker(host) { function getNormalizedType(type, writing) { while (true) { const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; - if (t === type) - return t; + if (t === type) return t; type = t; } } @@ -62640,8 +62686,7 @@ function createTypeChecker(host) { for (const t of type.types) { hasInstantiable || (hasInstantiable = !!(t.flags & 465829888 /* Instantiable */)); hasNullableOrEmpty || (hasNullableOrEmpty = !!(t.flags & 98304 /* Nullable */) || isEmptyAnonymousObjectType(t)); - if (hasInstantiable && hasNullableOrEmpty) - return true; + if (hasInstantiable && hasNullableOrEmpty) return true; } return false; } @@ -62852,10 +62897,8 @@ function createTypeChecker(host) { } function reportError(message, ...args) { Debug.assert(!!errorNode); - if (incompatibleStack) - reportIncompatibleStack(); - if (message.elidedInCompatabilityPyramid) - return; + if (incompatibleStack) reportIncompatibleStack(); + if (message.elidedInCompatabilityPyramid) return; if (skipParentCounter === 0) { errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); } else { @@ -62875,8 +62918,7 @@ function createTypeChecker(host) { } } function reportRelationError(message, source2, target2) { - if (incompatibleStack) - reportIncompatibleStack(); + if (incompatibleStack) reportIncompatibleStack(); const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2); let generalizedSource = source2; let generalizedSourceType = sourceType; @@ -62959,8 +63001,7 @@ function createTypeChecker(host) { return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { - if (originalSource === originalTarget) - return -1 /* True */; + if (originalSource === originalTarget) return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -62980,13 +63021,10 @@ function createTypeChecker(host) { /*writing*/ true ); - if (source2 === target2) - return -1 /* True */; + if (source2 === target2) return -1 /* True */; if (relation === identityRelation) { - if (source2.flags !== target2.flags) - return 0 /* False */; - if (source2.flags & 67358815 /* Singleton */) - return -1 /* True */; + if (source2.flags !== target2.flags) return 0 /* False */; + if (source2.flags & 67358815 /* Singleton */) return -1 /* True */; traceUnionsOrIntersectionsTooLarge(source2, target2); return recursiveTypeRelatedTo( source2, @@ -63009,12 +63047,10 @@ function createTypeChecker(host) { /*writing*/ true ); - if (source2 === target2) - return -1 /* True */; + if (source2 === target2) return -1 /* True */; } } - if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) - return -1 /* True */; + if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) return -1 /* True */; if (source2.flags & 469499904 /* StructuredOrInstantiable */ || target2.flags & 469499904 /* StructuredOrInstantiable */) { const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { @@ -63102,6 +63138,16 @@ function createTypeChecker(host) { errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); } if (!headMessage2 && maybeSuppress) { + const savedErrorState = captureErrorCalculationState(); + reportRelationError(headMessage2, source2, target2); + let canonical; + if (errorInfo && errorInfo !== savedErrorState.errorInfo) { + canonical = { code: errorInfo.code, messageText: errorInfo.messageText }; + } + resetErrorInfo(savedErrorState); + if (canonical && errorInfo) { + errorInfo.canonicalHead = canonical; + } lastSkippedInfo = [source2, target2]; return; } @@ -63174,8 +63220,7 @@ function createTypeChecker(host) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors2) { const errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget); - if (!errorNode) - return Debug.fail(); + if (!errorNode) return Debug.fail(); if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { if (prop.valueDeclaration && isJsxAttribute(prop.valueDeclaration) && getSourceFileOfNode(errorNode) === getSourceFileOfNode(prop.valueDeclaration.name)) { errorNode = prop.valueDeclaration.name; @@ -63594,14 +63639,12 @@ function createTypeChecker(host) { if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source2; sourceDepth++; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target2; targetDepth++; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) expandingFlags |= 2 /* Target */; } let originalHandler; let propagatingVarianceFlags = 0; @@ -64255,8 +64298,7 @@ function createTypeChecker(host) { } return 0 /* False */; function countMessageChainBreadth(info) { - if (!info) - return 0; + if (!info) return 0; return reduceLeft(info, (value, chain) => value + 1 + countMessageChainBreadth(chain.next), 0); } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState2) { @@ -64298,8 +64340,7 @@ function createTypeChecker(host) { var _a2; const sourceProperties = getPropertiesOfType(source2); const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2); - if (!sourcePropertiesFiltered) - return 0 /* False */; + if (!sourcePropertiesFiltered) return 0 /* False */; let numCombinations = 1; for (const sourceProperty of sourcePropertiesFiltered) { numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty)); @@ -64325,10 +64366,8 @@ function createTypeChecker(host) { for (let i = 0; i < sourcePropertiesFiltered.length; i++) { const sourceProperty = sourcePropertiesFiltered[i]; const targetProperty = getPropertyOfType(type, sourceProperty.escapedName); - if (!targetProperty) - continue outer; - if (sourceProperty === targetProperty) - continue; + if (!targetProperty) continue outer; + if (sourceProperty === targetProperty) continue; const related = propertyRelatedTo( source2, target2, @@ -64402,8 +64441,7 @@ function createTypeChecker(host) { return result2; } function excludeProperties(properties, excludedProperties) { - if (!excludedProperties || properties.length === 0) - return properties; + if (!excludedProperties || properties.length === 0) return properties; let result2; for (let i = 0; i < properties.length; i++) { if (!excludedProperties.has(properties[i].escapedName)) { @@ -65020,8 +65058,7 @@ function createTypeChecker(host) { return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) - return emptyArray; + if (isTupleType(source) && isTupleType(target)) return emptyArray; return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp))); } function isExactOptionalPropertyMismatch(source, target) { @@ -65090,6 +65127,7 @@ function createTypeChecker(host) { if (!links.variances) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); const oldVarianceComputation = inVarianceComputation; + const saveResolutionStart = resolutionStart; if (!inVarianceComputation) { inVarianceComputation = true; resolutionStart = resolutionTargets.length; @@ -65124,7 +65162,7 @@ function createTypeChecker(host) { } if (!oldVarianceComputation) { inVarianceComputation = false; - resolutionStart = 0; + resolutionStart = saveResolutionStart; } links.variances = variances; (_b = tracing) == null ? void 0 : _b.pop({ variances: variances.map(Debug.formatVariance) }); @@ -65964,12 +66002,17 @@ function createTypeChecker(host) { } } function applyToReturnTypes(source, target, callback) { - const sourceTypePredicate = getTypePredicateOfSignature(source); const targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) { - callback(sourceTypePredicate.type, targetTypePredicate.type); - } else { - callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (targetTypePredicate) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + return; + } + } + const targetReturnType = getReturnTypeOfSignature(target); + if (couldContainTypeVariables(targetReturnType)) { + callback(getReturnTypeOfSignature(source), targetReturnType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes) { @@ -66183,10 +66226,8 @@ function createTypeChecker(host) { reverseMappedSourceStack.push(source); reverseMappedTargetStack.push(target); const saveExpandingFlags = reverseExpandingFlags; - if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) - reverseExpandingFlags |= 1 /* Source */; - if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) - reverseExpandingFlags |= 2 /* Target */; + if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) reverseExpandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) reverseExpandingFlags |= 2 /* Target */; let type; if (reverseExpandingFlags !== 3 /* Both */) { type = inferReverseMappedTypeWorker(source, target, constraint); @@ -66261,8 +66302,7 @@ function createTypeChecker(host) { return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } function isValidNumberString(s, roundTripOnly) { - if (s === "") - return false; + if (s === "") return false; const n = +s; return isFinite(n) && (!roundTripOnly || "" + n === s); } @@ -66332,8 +66372,7 @@ function createTypeChecker(host) { const lastTargetIndex = targetTexts.length - 1; const targetStartText = targetTexts[0]; const targetEndText = targetTexts[lastTargetIndex]; - if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) - return void 0; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return void 0; const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); const matches = []; let seg = 0; @@ -66345,11 +66384,9 @@ function createTypeChecker(host) { let p = pos; while (true) { p = getSourceText(s).indexOf(delim, p); - if (p >= 0) - break; + if (p >= 0) break; s++; - if (s === sourceTexts.length) - return void 0; + if (s === sourceTexts.length) return void 0; p = 0; } addMatch(s, p); @@ -66592,10 +66629,8 @@ function createTypeChecker(host) { const saveExpandingFlags = expandingFlags; (sourceStack ?? (sourceStack = [])).push(source); (targetStack ?? (targetStack = [])).push(target); - if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) - expandingFlags |= 1 /* Source */; - if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) - expandingFlags |= 2 /* Target */; + if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { action(source, target); } else { @@ -66683,8 +66718,7 @@ function createTypeChecker(host) { const saveInferencePriority = inferencePriority; inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); - if (inferencePriority === priority) - matched[i] = true; + if (inferencePriority === priority) matched[i] = true; inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */; inferencePriority = Math.min(inferencePriority, saveInferencePriority); } @@ -66817,8 +66851,7 @@ function createTypeChecker(host) { inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); const sourceNameType = getNameTypeFromMappedType(source); const targetNameType = getNameTypeFromMappedType(target); - if (sourceNameType && targetNameType) - inferFromTypes(sourceNameType, targetNameType); + if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType); } function inferFromObjectTypes(source, target) { var _a, _b; @@ -67246,11 +67279,9 @@ function createTypeChecker(host) { /*ignoreErrors*/ true ); - if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) - return void 0; + if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) return void 0; const declaration = symbol.valueDeclaration; - if (declaration === void 0) - return void 0; + if (declaration === void 0) return void 0; const type = tryGetTypeFromEffectiveTypeNode(declaration); if (type) { const name = tryGetNameFromType(type); @@ -67334,8 +67365,7 @@ function createTypeChecker(host) { duplicate = true; } }); - if (!duplicate) - count++; + if (!duplicate) count++; } } } @@ -67542,8 +67572,7 @@ function createTypeChecker(host) { function getTypeOfDestructuredProperty(type, name) { var _a; const nameType = getLiteralTypeFromPropertyName(name); - if (!isTypeUsableAsPropertyName(nameType)) - return errorType; + if (!isTypeUsableAsPropertyName(nameType)) return errorType; const text = getPropertyNameFromType(nameType); return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.type) || errorType; } @@ -67557,8 +67586,7 @@ function createTypeChecker(host) { )) || errorType; } function includeUndefinedInIndexSignature(type) { - if (!type) - return type; + if (!type) return type; return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type; } function getTypeOfDestructuredSpreadExpression(type) { @@ -68857,7 +68885,7 @@ function createTypeChecker(host) { if (!hasDefaultClause) { return caseType; } - const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t))))); + const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, t.flags & 32768 /* Undefined */ ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t))))); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByTypeName(type, typeName) { @@ -69308,7 +69336,7 @@ function createTypeChecker(host) { function parameterInitializerContainsUndefined(declaration) { const links = getNodeLinks(declaration); if (links.parameterInitializerContainsUndefined === void 0) { - if (!pushTypeResolution(declaration, 9 /* ParameterInitializerContainsUndefined */)) { + if (!pushTypeResolution(declaration, 8 /* ParameterInitializerContainsUndefined */)) { reportCircularityError(declaration.symbol); return true; } @@ -69317,7 +69345,7 @@ function createTypeChecker(host) { reportCircularityError(declaration.symbol); return true; } - links.parameterInitializerContainsUndefined = containsUndefined; + links.parameterInitializerContainsUndefined ?? (links.parameterInitializerContainsUndefined = containsUndefined); } return links.parameterInitializerContainsUndefined; } @@ -69344,6 +69372,9 @@ function createTypeChecker(host) { return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { + if (isNoInferType(type)) { + type = type.baseType; + } const substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } @@ -69362,6 +69393,248 @@ function createTypeChecker(host) { return false; }); } + function markLinkedReferences(location, hint, propSymbol, parentType) { + if (!canCollectSymbolAliasAccessabilityData) { + return; + } + if (location.flags & 33554432 /* Ambient */) { + return; + } + switch (hint) { + case 1 /* Identifier */: + return markIdentifierAliasReferenced(location); + case 2 /* Property */: + return markPropertyAliasReferenced(location, propSymbol, parentType); + case 3 /* ExportAssignment */: + return markExportAssignmentAliasReferenced(location); + case 4 /* Jsx */: + return markJsxAliasReferenced(location); + case 5 /* AsyncFunction */: + return markAsyncFunctionAliasReferenced(location); + case 6 /* ExportImportEquals */: + return markImportEqualsAliasReferenced(location); + case 7 /* ExportSpecifier */: + return markExportSpecifierAliasReferenced(location); + case 8 /* Decorator */: + return markDecoratorAliasReferenced(location); + case 0 /* Unspecified */: { + if (isIdentifier(location) && (isExpressionNode(location) || isShorthandPropertyAssignment(location.parent) || isImportEqualsDeclaration(location.parent) && location.parent.moduleReference === location) && shouldMarkIdentifierAliasReferenced(location)) { + if (isPropertyAccessOrQualifiedName(location.parent)) { + const left = isPropertyAccessExpression(location.parent) ? location.parent.expression : location.parent.left; + if (left !== location) return; + } + markIdentifierAliasReferenced(location); + return; + } + if (isPropertyAccessOrQualifiedName(location)) { + let topProp = location; + while (isPropertyAccessOrQualifiedName(topProp)) { + if (isPartOfTypeNode(topProp)) return; + topProp = topProp.parent; + } + return markPropertyAliasReferenced(location); + } + if (isExportAssignment(location)) { + return markExportAssignmentAliasReferenced(location); + } + if (isJsxOpeningLikeElement(location) || isJsxOpeningFragment(location)) { + return markJsxAliasReferenced(location); + } + if (isImportEqualsDeclaration(location)) { + if (isInternalModuleImportEqualsDeclaration(location) || checkExternalImportOrExportDeclaration(location)) { + return markImportEqualsAliasReferenced(location); + } + return; + } + if (isExportSpecifier(location)) { + return markExportSpecifierAliasReferenced(location); + } + if (isFunctionLikeDeclaration(location) || isMethodSignature(location)) { + markAsyncFunctionAliasReferenced(location); + } + if (!compilerOptions.emitDecoratorMetadata) { + return; + } + if (!canHaveDecorators(location) || !hasDecorators(location) || !location.modifiers || !nodeCanBeDecorated(legacyDecorators, location, location.parent, location.parent.parent)) { + return; + } + return markDecoratorAliasReferenced(location); + } + default: + Debug.assertNever(hint, `Unhandled reference hint: ${hint}`); + } + } + function markIdentifierAliasReferenced(location) { + const symbol = getResolvedSymbol(location); + if (symbol && symbol !== argumentsSymbol && symbol !== unknownSymbol && !isThisInTypeQuery(location)) { + markAliasReferenced(symbol, location); + } + } + function markPropertyAliasReferenced(location, propSymbol, parentType) { + const left = isPropertyAccessExpression(location) ? location.expression : location.left; + if (isThisIdentifier(left) || !isIdentifier(left)) { + return; + } + const parentSymbol = getResolvedSymbol(left); + if (!parentSymbol || parentSymbol === unknownSymbol) { + return; + } + if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location)) { + markAliasReferenced(parentSymbol, location); + return; + } + const leftType = parentType || checkExpressionCached(left); + if (isTypeAny(leftType) || leftType === silentNeverType) { + markAliasReferenced(parentSymbol, location); + return; + } + let prop = propSymbol; + if (!prop && !parentType) { + const right = isPropertyAccessExpression(location) ? location.name : location.right; + const lexicallyScopedSymbol = isPrivateIdentifier(right) && lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + const assignmentKind = getAssignmentTargetKind(location); + const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(location) ? getWidenedType(leftType) : leftType); + prop = isPrivateIdentifier(right) ? lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(apparentType, lexicallyScopedSymbol) || void 0 : getPropertyOfType(apparentType, right.escapedText); + } + if (!(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && location.parent.kind === 306 /* EnumMember */))) { + markAliasReferenced(parentSymbol, location); + } + return; + } + function markExportAssignmentAliasReferenced(location) { + if (isIdentifier(location.expression)) { + const id = location.expression; + const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( + id, + -1 /* All */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + )); + if (sym) { + markAliasReferenced(sym, id); + } + } + } + function markJsxAliasReferenced(node) { + if (!getJsxNamespaceContainerForImplicitImport(node)) { + const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.Cannot_find_name_0 : void 0; + const jsxFactoryNamespace = getJsxNamespace(node); + const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node; + let jsxFactorySym; + if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { + jsxFactorySym = resolveName( + jsxFactoryLocation, + jsxFactoryNamespace, + 111551 /* Value */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + if (jsxFactorySym) { + jsxFactorySym.isReferenced = -1 /* All */; + if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) { + markAliasSymbolAsReferenced(jsxFactorySym); + } + } + if (isJsxOpeningFragment(node)) { + const file = getSourceFileOfNode(node); + const localJsxNamespace = getLocalJsxNamespace(file); + if (localJsxNamespace) { + resolveName( + jsxFactoryLocation, + localJsxNamespace, + 111551 /* Value */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + } + } + return; + } + function markAsyncFunctionAliasReferenced(location) { + if (languageVersion < 2 /* ES2015 */) { + if (getFunctionFlags(location) & 2 /* Async */) { + const returnTypeNode = getEffectiveReturnTypeNode(location); + markTypeNodeAsReferenced(returnTypeNode); + } + } + } + function markImportEqualsAliasReferenced(location) { + if (hasSyntacticModifier(location, 32 /* Export */)) { + markExportAsReferenced(location); + } + } + function markExportSpecifierAliasReferenced(location) { + if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) { + const exportedName = location.propertyName || location.name; + const symbol = resolveName( + exportedName, + exportedName.escapedText, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + } else { + const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); + if (!target || getSymbolFlags(target) & 111551 /* Value */) { + markExportAsReferenced(location); + markIdentifierAliasReferenced(location.propertyName || location.name); + } + } + return; + } + } + function markDecoratorAliasReferenced(node) { + if (compilerOptions.emitDecoratorMetadata) { + const firstDecorator = find(node.modifiers, isDecorator); + if (!firstDecorator) { + return; + } + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + switch (node.kind) { + case 263 /* ClassDeclaration */: + const constructor = getFirstConstructorWithBody(node); + if (constructor) { + for (const parameter of constructor.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; + const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 174 /* MethodDeclaration */: + for (const parameter of node.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); + break; + case 172 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); + break; + case 169 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + const containingSignature = node.parent; + for (const parameter of containingSignature.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); + break; + } + } + } function markAliasReferenced(symbol, location) { if (!canCollectSymbolAliasAccessabilityData) { return; @@ -69379,12 +69652,81 @@ function createTypeChecker(host) { ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); - } else { - markConstEnumAliasAsReferenced(symbol); } } } } + function markAliasSymbolAsReferenced(symbol) { + Debug.assert(canCollectSymbolAliasAccessabilityData); + const links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + if (isInternalModuleImportEqualsDeclaration(node)) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + const left = getFirstIdentifier(node.moduleReference); + markIdentifierAliasReferenced(left); + } + } + } + } + function markExportAsReferenced(node) { + const symbol = getSymbolOfDeclaration(node); + const target = resolveAlias(symbol); + if (target) { + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { + if (!typeName) return; + const rootName = getFirstIdentifier(typeName); + const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + const rootSymbol = resolveName( + rootName, + rootName.escapedText, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { + if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { + markAliasSymbolAsReferenced(rootSymbol); + } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { + const diag2 = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); + const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); + if (aliasDeclaration) { + addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); + } + } + } + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference( + node && getEntityNameFromTypeNode(node), + /*forDecoratorMetadata*/ + false + ); + } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + const entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference( + entityName, + /*forDecoratorMetadata*/ + true + ); + } + } function getNarrowedTypeOfSymbol(symbol, location, checkMode) { var _a; const type = getTypeOfSymbol(symbol, checkMode); @@ -69447,18 +69789,12 @@ function createTypeChecker(host) { } return type; } - function checkIdentifier(node, checkMode) { - if (isThisInTypeQuery(node)) { - return checkThisExpression(node); - } - const symbol = getResolvedSymbol(node); - if (symbol === unknownSymbol) { - return errorType; - } + function checkIdentifierCalculateNodeCheckFlags(node, symbol) { + if (isThisInTypeQuery(node)) return; if (symbol === argumentsSymbol) { if (isInPropertyInitializerOrClassStaticBlock(node)) { error(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers); - return errorType; + return; } let container = getContainingFunction(node); if (container) { @@ -69477,17 +69813,14 @@ function createTypeChecker(host) { } } } - return getTypeOfSymbol(symbol); - } - if (shouldMarkIdentifierAliasReferenced(node)) { - markAliasReferenced(symbol, node); + return; } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } - let declaration = localOrExportSymbol.valueDeclaration; + const declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( @@ -69514,6 +69847,27 @@ function createTypeChecker(host) { } } checkNestedBlockScopedBinding(node, symbol); + } + function checkIdentifier(node, checkMode) { + if (isThisInTypeQuery(node)) { + return checkThisExpression(node); + } + const symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + checkIdentifierCalculateNodeCheckFlags(node, symbol); + if (symbol === argumentsSymbol) { + if (isInPropertyInitializerOrClassStaticBlock(node)) { + return errorType; + } + return getTypeOfSymbol(symbol); + } + if (shouldMarkIdentifierAliasReferenced(node)) { + markLinkedReferences(node, 1 /* Identifier */); + } + const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + let declaration = localOrExportSymbol.valueDeclaration; let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node, checkMode); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { @@ -69880,8 +70234,7 @@ function createTypeChecker(host) { let inAsyncFunction = false; if (!isCallExpression2) { while (container && container.kind === 219 /* ArrowFunction */) { - if (hasSyntacticModifier(container, 1024 /* Async */)) - inAsyncFunction = true; + if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; container = getSuperContainer( container, /*stopOnFunctions*/ @@ -69889,8 +70242,7 @@ function createTypeChecker(host) { ); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } - if (container && hasSyntacticModifier(container, 1024 /* Async */)) - inAsyncFunction = true; + if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; } let nodeCheckFlag = 0; if (!container || !isLegalUsageOfSuperExpression(container)) { @@ -70101,12 +70453,10 @@ function createTypeChecker(host) { const parent = declaration.parent.parent; const name = declaration.propertyName || declaration.name; const parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 208 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); - if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) - return void 0; + if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0; if (parent.name.kind === 207 /* ArrayBindingPattern */) { const index = indexOfNode(declaration.parent.elements, declaration); - if (index < 0) - return void 0; + if (index < 0) return void 0; return getContextualTypeForElementExpression(parentType, index); } const nameType = getLiteralTypeFromPropertyName(name); @@ -70117,8 +70467,7 @@ function createTypeChecker(host) { } function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { const parentType = isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags); - if (!parentType) - return void 0; + if (!parentType) return void 0; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfDeclaration(declaration).escapedName); } function getContextualTypeForInitializerExpression(node, contextFlags) { @@ -70184,7 +70533,31 @@ function createTypeChecker(host) { if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) { contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); } - return node.asteriskToken ? contextualReturnType : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); + if (node.asteriskToken) { + const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator); + const yieldType = (iterationTypes == null ? void 0 : iterationTypes.yieldType) ?? silentNeverType; + const returnType = getContextualType(node, contextFlags) ?? silentNeverType; + const nextType = (iterationTypes == null ? void 0 : iterationTypes.nextType) ?? unknownType; + const generatorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + false + ); + if (isAsyncGenerator) { + const asyncGeneratorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + true + ); + return getUnionType([generatorType, asyncGeneratorType]); + } + return generatorType; + } + return getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); } } return void 0; @@ -70415,8 +70788,7 @@ function createTypeChecker(host) { return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration); } function getContextualTypeForThisPropertyAssignment(binaryExpression) { - if (!binaryExpression.symbol) - return getTypeOfExpression(binaryExpression.left); + if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); if (annotated) { @@ -70637,60 +71009,70 @@ function createTypeChecker(host) { return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems( - contextualType, - concatenate( - map( - filter(node.properties, (p) => { - if (!p.symbol) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + return getCachedType(key) ?? setCachedType( + key, + getMatchingUnionConstituentForObjectLiteral(contextualType, node) ?? discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => { + if (!p.symbol) { + return false; + } + if (p.kind === 303 /* PropertyAssignment */) { + return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + if (p.kind === 304 /* ShorthandPropertyAssignment */) { + return isDiscriminantProperty(contextualType, p.symbol.escapedName); + } return false; - } - if (p.kind === 303 /* PropertyAssignment */) { - return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); - } - if (p.kind === 304 /* ShorthandPropertyAssignment */) { - return isDiscriminantProperty(contextualType, p.symbol.escapedName); - } - return false; - }), - (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] + }), + (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) ), - map( - filter(getPropertiesOfType(contextualType), (s) => { - var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); - }), - (s) => [() => undefinedType, s.escapedName] - ) - ), - isTypeAssignableTo + isTypeAssignableTo + ) ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + const cached = getCachedType(key); + if (cached) return cached; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return discriminateTypeByDiscriminableItems( - contextualType, - concatenate( - map( - filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), - (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + return setCachedType( + key, + discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), + (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) ), - map( - filter(getPropertiesOfType(contextualType), (s) => { - var _a; - if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { - return false; - } - const element = node.parent.parent; - if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { - return false; - } - return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); - }), - (s) => [() => undefinedType, s.escapedName] - ) - ), - isTypeAssignableTo + isTypeAssignableTo + ) ); } function getApparentTypeOfContextualType(node, contextFlags) { @@ -70966,8 +71348,7 @@ function createTypeChecker(host) { if (typeParams) { const inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context)); libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs)); - } else - libraryManagedAttributeType = intrinsicClassAttribs; + } else libraryManagedAttributeType = intrinsicClassAttribs; apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType); } const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -71124,7 +71505,7 @@ function createTypeChecker(host) { } function checkGrammarRegularExpressionLiteral(node) { const sourceFile = getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { + if (!hasParseDiagnostics(sourceFile) && !node.isUnterminated) { let lastError; scanner ?? (scanner = createScanner( 99 /* ESNext */, @@ -71339,8 +71720,7 @@ function createTypeChecker(host) { const links = getSymbolLinks(symbol); if (!links.immediateTarget) { const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration( node, /*dontRecursivelyResolve*/ @@ -71515,12 +71895,9 @@ function createTypeChecker(host) { return createObjectLiteralType(); function createObjectLiteralType() { const indexInfos = []; - if (hasComputedStringProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType)); - if (hasComputedNumberProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType)); - if (hasComputedSymbolProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType)); + if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType)); + if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType)); + if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType)); const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos); result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { @@ -71760,8 +72137,7 @@ function createTypeChecker(host) { if (!links.resolvedSymbol) { const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (!isErrorType(intrinsicElementsType)) { - if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) - return Debug.fail(); + if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail(); const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName); if (intrinsicProp) { @@ -71803,11 +72179,7 @@ function createTypeChecker(host) { } const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; - const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0; - const specifier = file == null ? void 0 : file.imports[jsxImportIndex]; - if (specifier) { - Debug.assert(nodeIsSynthesized(specifier) && specifier.text === runtimeImportSpecifier, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`); - } + const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier); const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location); const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0; if (links) { @@ -71973,8 +72345,7 @@ function createTypeChecker(host) { } function getJsxElementClassTypeAt(location) { const type = getJsxType(JsxNames.ElementClass, location); - if (isErrorType(type)) - return void 0; + if (isErrorType(type)) return void 0; return type; } function getJsxElementTypeAt(location) { @@ -71988,14 +72359,11 @@ function createTypeChecker(host) { } function getJsxElementTypeTypeAt(location) { const ns = getJsxNamespaceAt(location); - if (!ns) - return void 0; + if (!ns) return void 0; const sym = getJsxElementTypeSymbol(ns); - if (!sym) - return void 0; + if (!sym) return void 0; const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); - if (!type || isErrorType(type)) - return void 0; + if (!type || isErrorType(type)) return void 0; return type; } function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { @@ -72033,42 +72401,7 @@ function createTypeChecker(host) { checkGrammarJsxElement(node); } checkJsxPreconditions(node); - if (!getJsxNamespaceContainerForImplicitImport(node)) { - const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.Cannot_find_name_0 : void 0; - const jsxFactoryNamespace = getJsxNamespace(node); - const jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node; - let jsxFactorySym; - if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { - jsxFactorySym = resolveName( - jsxFactoryLocation, - jsxFactoryNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - /*isUse*/ - true - ); - } - if (jsxFactorySym) { - jsxFactorySym.isReferenced = -1 /* All */; - if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) { - markAliasSymbolAsReferenced(jsxFactorySym); - } - } - if (isJsxOpeningFragment(node)) { - const file = getSourceFileOfNode(node); - const localJsxNamespace = getLocalJsxNamespace(file); - if (localJsxNamespace) { - resolveName( - jsxFactoryLocation, - localJsxNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - /*isUse*/ - true - ); - } - } - } + markLinkedReferences(node, 4 /* Jsx */); if (isNodeOpeningLikeElement) { const jsxOpeningLikeNode = node; const sig = getResolvedSignature(jsxOpeningLikeNode); @@ -72499,7 +72832,13 @@ function createTypeChecker(host) { } else { if (isAnyLike) { if (isIdentifier(left) && parentSymbol) { - markAliasReferenced(parentSymbol, node); + markLinkedReferences( + node, + 2 /* Property */, + /*propSymbol*/ + void 0, + leftType + ); } return isErrorType(apparentType) ? errorType : apparentType; } @@ -72512,9 +72851,7 @@ function createTypeChecker(host) { node.kind === 166 /* QualifiedName */ ); } - if (isIdentifier(left) && parentSymbol && (getIsolatedModules(compilerOptions) || !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && node.parent.kind === 306 /* EnumMember */)) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { - markAliasReferenced(parentSymbol, node); - } + markLinkedReferences(node, 2 /* Property */, prop, leftType); let propType; if (!prop) { const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0; @@ -72788,8 +73125,7 @@ function createTypeChecker(host) { } function getSuggestionForSymbolNameLookup(symbols, name, meaning) { const symbol = getSymbol(symbols, name, meaning); - if (symbol) - return symbol; + if (symbol) return symbol; let candidates; if (symbols === globals) { const primitives = mapDefined( @@ -73413,8 +73749,7 @@ function createTypeChecker(host) { for (const sig of callSignatures) { const firstparam = getTypeAtPosition(sig, 0); const signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */); - if (!length(signaturesOfParam)) - continue; + if (!length(signaturesOfParam)) continue; for (const paramSig of signaturesOfParam) { hasFirstParamSignatures = true; if (hasEffectiveRestParameter(paramSig)) { @@ -73671,8 +74006,7 @@ function createTypeChecker(host) { return callLike; } function isPromiseResolveArityError(node) { - if (!isCallExpression(node) || !isIdentifier(node.expression)) - return false; + if (!isCallExpression(node) || !isIdentifier(node.expression)) return false; const symbol = resolveName( node.expression, node.expression.escapedText, @@ -73690,8 +74024,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ); - if (!globalPromiseSymbol) - return false; + if (!globalPromiseSymbol) return false; const constructorSymbol = getSymbolAtLocation( decl.parent.parent.expression, /*ignoreErrors*/ @@ -73718,10 +74051,8 @@ function createTypeChecker(host) { closestSignature = sig; } max = Math.max(max, maxParameter); - if (minParameter < args.length && minParameter > maxBelow) - maxBelow = minParameter; - if (args.length < maxParameter && maxParameter < minAbove) - minAbove = maxParameter; + if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter; } const hasRestParameter2 = some(signatures, hasEffectiveRestParameter); const parameterRange = hasRestParameter2 ? min2 : min2 < max ? min2 + "-" + max : min2; @@ -74519,8 +74850,7 @@ function createTypeChecker(host) { const importNode = getSymbolLinks(apparentType.symbol).originatingImport; if (importNode && !isImportCall(importNode)) { const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); - if (!sigs || !sigs.length) - return; + if (!sigs || !sigs.length) return; addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } @@ -74726,8 +75056,13 @@ function createTypeChecker(host) { if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } + const saveResolutionStart = resolutionStart; + if (!cached) { + resolutionStart = resolutionTargets.length; + } links.resolvedSignature = resolvingSignature; let result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */); + resolutionStart = saveResolutionStart; if (result !== resolvingSignature) { if (links.resolvedSignature !== resolvingSignature) { result = links.resolvedSignature; @@ -74743,10 +75078,8 @@ function createTypeChecker(host) { } const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0; if (func) { - if (getJSDocClassTag(node)) - return true; - if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) - return false; + if (getJSDocClassTag(node)) return true; + if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false; const symbol = getSymbolOfDeclaration(func); return !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size); } @@ -74891,8 +75224,7 @@ function createTypeChecker(host) { return returnType; } function checkDeprecatedSignature(signature, node) { - if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) - return; + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -74923,8 +75255,7 @@ function createTypeChecker(host) { } } function isSymbolOrSymbolForCall(node) { - if (!isCallExpression(node)) - return false; + if (!isCallExpression(node)) return false; let left = node.expression; if (isPropertyAccessExpression(left) && left.name.escapedText === "for") { left = left.expression; @@ -75054,8 +75385,7 @@ function createTypeChecker(host) { )) { return false; } - if (!isIdentifier(node.expression)) - return Debug.fail(); + if (!isIdentifier(node.expression)) return Debug.fail(); const resolvedRequire = resolveName( node.expression, node.expression.escapedText, @@ -75079,8 +75409,7 @@ function createTypeChecker(host) { return false; } function checkTaggedTemplateExpression(node) { - if (!checkGrammarTaggedTemplateChain(node)) - checkGrammarTypeArguments(node, node.typeArguments); + if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments); if (languageVersion < 2 /* TaggedTemplates */) { checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */); } @@ -75758,8 +76087,7 @@ function createTypeChecker(host) { case 177 /* GetAccessor */: case 178 /* SetAccessor */: { const node = parent; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node); const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; @@ -75770,8 +76098,7 @@ function createTypeChecker(host) { } case 172 /* PropertyDeclaration */: { const node = parent; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const valueType = getTypeOfNode(node); const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType; @@ -75836,8 +76163,7 @@ function createTypeChecker(host) { case 178 /* SetAccessor */: case 172 /* PropertyDeclaration */: { const node = parent; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const targetType = getParentTypeOfClassElement(node); const targetParam = createParameter("target", targetType); const keyType = getClassElementPropertyKeyType(node); @@ -75977,12 +76303,9 @@ function createTypeChecker(host) { returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); - if (nextType) - reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); + if (yieldType) reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType( @@ -75999,15 +76322,12 @@ function createTypeChecker(host) { returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync); } } - if (yieldType) - yieldType = getWidenedType(yieldType); - if (returnType) - returnType = getWidenedType(returnType); - if (nextType) - nextType = getWidenedType(nextType); + if (yieldType) yieldType = getWidenedType(yieldType); + if (returnType) returnType = getWidenedType(returnType); + if (nextType) nextType = getWidenedType(nextType); } if (isGenerator) { - return createGeneratorReturnType( + return createGeneratorType( yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, @@ -76017,7 +76337,7 @@ function createTypeChecker(host) { return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType; } } - function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) { + function createGeneratorType(yieldType, returnType, nextType, isAsyncGenerator) { const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; const globalGeneratorType = resolver.getGlobalGeneratorType( /*reportErrors*/ @@ -76086,8 +76406,7 @@ function createTypeChecker(host) { void 0 ); } - if (nextType) - pushIfUnique(nextTypes, nextType); + if (nextType) pushIfUnique(nextTypes, nextType); }); return { yieldTypes, nextTypes }; } @@ -76216,19 +76535,16 @@ function createTypeChecker(host) { return void 0; } const functionFlags = getFunctionFlags(func); - if (functionFlags !== 0 /* Normal */) - return void 0; + if (functionFlags !== 0 /* Normal */) return void 0; let singleReturn; if (func.body && func.body.kind !== 241 /* Block */) { singleReturn = func.body; } else { const bailedEarly = forEachReturnStatement(func.body, (returnStatement) => { - if (singleReturn || !returnStatement.expression) - return true; + if (singleReturn || !returnStatement.expression) return true; singleReturn = returnStatement.expression; }); - if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) - return void 0; + if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return void 0; } return checkIfExpressionRefinesAnyParameter(func, singleReturn); } @@ -76239,8 +76555,7 @@ function createTypeChecker(host) { true ); const returnType = checkExpressionCached(expr); - if (!(returnType.flags & 16 /* Boolean */)) - return void 0; + if (!(returnType.flags & 16 /* Boolean */)) return void 0; return forEach(func.parameters, (param, i) => { const initType = getTypeOfSymbol(param.symbol); if (!initType || initType.flags & 16 /* Boolean */ || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) { @@ -76262,8 +76577,7 @@ function createTypeChecker(host) { ); const trueCondition = createFlowNode(32 /* TrueCondition */, expr, antecedent); const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition); - if (trueType2 === initType) - return void 0; + if (trueType2 === initType) return void 0; const falseCondition = createFlowNode(64 /* FalseCondition */, expr, antecedent); const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition); return falseSubtype.flags & 131072 /* Never */ ? trueType2 : void 0; @@ -77371,12 +77685,10 @@ function createTypeChecker(host) { const sourceText = sf.text; const start = skipTrivia(sourceText, left.pos); const isInDiag2657 = sf.parseDiagnostics.some((diag2) => { - if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) - return false; + if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false; return textSpanContainsPosition(diag2, start); }); - if (!isInDiag2657) - error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + if (!isInDiag2657) error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; default: @@ -77533,8 +77845,7 @@ function createTypeChecker(host) { const isRightNaN = isGlobalNaN(skipParentheses(right2)); if (isLeftNaN || isRightNaN) { const err = error(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */)); - if (isLeftNaN && isRightNaN) - return; + if (isLeftNaN && isRightNaN) return; const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */) : ""; const location = isLeftNaN ? right2 : left2; const expression = skipParentheses(location); @@ -77563,8 +77874,7 @@ function createTypeChecker(host) { function checkYieldExpression(node) { addLazyDiagnostic(checkYieldExpressionGrammar); const func = getContainingFunction(node); - if (!func) - return anyType; + if (!func) return anyType; const functionFlags = getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { return anyType; @@ -77650,6 +77960,10 @@ function createTypeChecker(host) { texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } + const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value; + if (evaluated) { + return getFreshTypeOfLiteralType(getStringLiteralType(evaluated)); + } if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType( node, /*contextFlags*/ @@ -77657,8 +77971,7 @@ function createTypeChecker(host) { ) || unknownType, isTemplateLiteralContextualType)) { return getTemplateLiteralType(texts, types); } - const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value; - return evaluated ? getFreshTypeOfLiteralType(getStringLiteralType(evaluated)) : stringType; + return stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); @@ -77936,8 +78249,7 @@ function createTypeChecker(host) { } function getUniqueTypeParameterName(typeParameters, baseName) { let len = baseName.length; - while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) - len--; + while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) len--; const s = baseName.slice(0, len); for (let index = 1; true; index++) { const augmentedName = s + index; @@ -78410,7 +78722,7 @@ function createTypeChecker(host) { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType; - const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); + const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode); } function checkClassForDuplicateDeclarations(node) { @@ -78556,8 +78868,7 @@ function createTypeChecker(host) { } } function checkPropertyDeclaration(node) { - if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) { @@ -78571,8 +78882,7 @@ function createTypeChecker(host) { return checkPropertyDeclaration(node); } function checkMethodDeclaration(node) { - if (!checkGrammarMethod(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") { error(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); } @@ -78607,8 +78917,7 @@ function createTypeChecker(host) { } function checkConstructorDeclaration(node) { checkSignatureDeclaration(node); - if (!checkGrammarConstructorTypeParameters(node)) - checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); const symbol = getSymbolOfDeclaration(node); const firstDeclaration = getDeclarationOfKind(symbol, node.kind); @@ -78683,8 +78992,7 @@ function createTypeChecker(host) { checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); function checkAccessorDeclarationDiagnostics() { - if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 177 /* GetAccessor */) { @@ -78806,11 +79114,9 @@ function createTypeChecker(host) { } function getTypeArgumentConstraint(node) { const typeReferenceNode = tryCast(node.parent, isTypeReferenceType); - if (!typeReferenceNode) - return void 0; + if (!typeReferenceNode) return void 0; const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReferenceNode); - if (!typeParameters) - return void 0; + if (!typeParameters) return void 0; const constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters))); } @@ -79391,10 +79697,7 @@ function createTypeChecker(host) { } function createAwaitedTypeIfNeeded(type) { if (isAwaitedTypeNeeded(type)) { - const awaitedType = tryCreateAwaitedType(type); - if (awaitedType) { - return awaitedType; - } + return tryCreateAwaitedType(type) ?? type; } Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like."); return type; @@ -79481,7 +79784,7 @@ function createTypeChecker(host) { return; } } else { - markTypeNodeAsReferenced(returnTypeNode); + markLinkedReferences(node, 5 /* AsyncFunction */); if (isErrorType(returnType)) { return; } @@ -79605,8 +79908,7 @@ function createTypeChecker(host) { return; } const decoratorSignature = getDecoratorCallSignature(node); - if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) - return; + if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) return; let headMessage; const expectedReturnType = decoratorSignature.resolvedReturnType; switch (node.parent.kind) { @@ -79666,49 +79968,6 @@ function createTypeChecker(host) { voidType ); } - function markTypeNodeAsReferenced(node) { - markEntityNameOrEntityExpressionAsReference( - node && getEntityNameFromTypeNode(node), - /*forDecoratorMetadata*/ - false - ); - } - function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { - if (!typeName) - return; - const rootName = getFirstIdentifier(typeName); - const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; - const rootSymbol = resolveName( - rootName, - rootName.escapedText, - meaning, - /*nameNotFoundMessage*/ - void 0, - /*isUse*/ - true - ); - if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { - if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { - markAliasSymbolAsReferenced(rootSymbol); - } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { - const diag2 = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); - const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration); - if (aliasDeclaration) { - addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); - } - } - } - } - function markDecoratorMedataDataTypeNodeAsReferenced(node) { - const entityName = getEntityNameForDecoratorMetadata(node); - if (entityName && isEntityName(entityName)) { - markEntityNameOrEntityExpressionAsReference( - entityName, - /*forDecoratorMetadata*/ - true - ); - } - } function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { @@ -79788,42 +80047,7 @@ function createTypeChecker(host) { } } } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); - switch (node.kind) { - case 263 /* ClassDeclaration */: - const constructor = getFirstConstructorWithBody(node); - if (constructor) { - for (const parameter of constructor.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 177 /* GetAccessor */: - case 178 /* SetAccessor */: - const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; - const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); - markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); - break; - case 174 /* MethodDeclaration */: - for (const parameter of node.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); - break; - case 172 /* PropertyDeclaration */: - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); - break; - case 169 /* Parameter */: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - const containingSignature = node.parent; - for (const parameter of containingSignature.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); - break; - } - } + markLinkedReferences(node, 8 /* Decorator */); for (const modifier of node.modifiers) { if (isDecorator(modifier)) { checkDecorator(modifier); @@ -80093,13 +80317,11 @@ function createTypeChecker(host) { } function checkUnusedTypeParameters(node, addDiagnostic) { const declarations = getSymbolOfDeclaration(node).declarations; - if (!declarations || last(declarations) !== node) - return; + if (!declarations || last(declarations) !== node) return; const typeParameters = getEffectiveTypeParameterDeclarations(node); const seenParentsWithEveryUnused = /* @__PURE__ */ new Set(); for (const typeParameter of typeParameters) { - if (!isTypeParameterUnused(typeParameter)) - continue; + if (!isTypeParameterUnused(typeParameter)) continue; const name = idText(typeParameter.name); const { parent } = typeParameter; if (parent.kind !== 195 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { @@ -80193,8 +80415,7 @@ function createTypeChecker(host) { unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused) ); } else { - for (const unused of unuseds) - errorUnusedLocal(unused, idText(unused.name), addDiagnostic); + for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic); } }); unusedDestructures.forEach(([bindingPattern, bindingElements]) => { @@ -80406,8 +80627,7 @@ function createTypeChecker(host) { } } function checkCollisionsForDeclarationName(node, name) { - if (!name) - return; + if (!name) return; checkCollisionWithRequireExportsInGeneratedCode(node, name); checkCollisionWithGlobalPromiseInGeneratedCode(node, name); recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name); @@ -80427,8 +80647,7 @@ function createTypeChecker(host) { } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { - if (!isIdentifier(node.name)) - return Debug.fail(); + if (!isIdentifier(node.name)) return Debug.fail(); const localDeclarationSymbol = resolveName( node, node.name.escapedText, @@ -80667,8 +80886,7 @@ function createTypeChecker(host) { forEach(node.declarations, checkSourceElement); } function checkVariableStatement(node) { - if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) - checkGrammarForDisallowedBlockScopedVariableStatement(node); + if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); checkVariableDeclarationList(node.declarationList); } function checkExpressionStatement(node) { @@ -80686,8 +80904,7 @@ function createTypeChecker(host) { checkSourceElement(node.elseStatement); } function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) { - if (!strictNullChecks) - return; + if (!strictNullChecks) return; bothHelper(condExpr, body); function bothHelper(condExpr2, body2) { condExpr2 = skipParentheses(condExpr2); @@ -80712,8 +80929,7 @@ function createTypeChecker(host) { return; } const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) - return; + if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return; const callSignatures = getSignaturesOfType(type, 0 /* Call */); const isPromise = !!getAwaitedTypeOfPromise(type); if (callSignatures.length === 0 && !isPromise) { @@ -80821,10 +81037,8 @@ function createTypeChecker(host) { checkExpression(node.initializer); } } - if (node.condition) - checkTruthinessExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); + if (node.condition) checkTruthinessExpression(node.condition); + if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); if (node.locals) { registerForUnusedIdentifiersCheck(node); @@ -81094,8 +81308,7 @@ function createTypeChecker(host) { } const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; const cachedTypes2 = getCachedIterationTypes(type, cacheKey); - if (cachedTypes2) - return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2; + if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2; let allIterationTypes; for (const constituent of type.types) { const errorOutputContainer = errorNode ? { errors: void 0 } : void 0; @@ -81121,10 +81334,8 @@ function createTypeChecker(host) { return iterationTypes === noIterationTypes ? void 0 : iterationTypes; } function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) { - if (iterationTypes === noIterationTypes) - return noIterationTypes; - if (iterationTypes === anyIterationTypes) - return anyIterationTypes; + if (iterationTypes === noIterationTypes) return noIterationTypes; + if (iterationTypes === anyIterationTypes) return anyIterationTypes; const { yieldType, returnType, nextType } = iterationTypes; if (errorNode) { getGlobalAwaitedSymbol( @@ -81512,8 +81723,7 @@ function createTypeChecker(host) { ); } function checkBreakOrContinueStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) - checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node); } function unwrapReturnType(returnType, functionFlags) { const isGenerator = !!(functionFlags & 1 /* Generator */); @@ -81745,8 +81955,7 @@ function createTypeChecker(host) { const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0; const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0; for (const info of indexInfos) { - if (info === checkInfo) - continue; + if (info === checkInfo) continue; const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) { @@ -81777,8 +81986,7 @@ function createTypeChecker(host) { } function checkUnmatchedJSDocParameters(node) { const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag); - if (!length(jsdocParameters)) - return; + if (!length(jsdocParameters)) return; const isJs = isInJSFile(node); const parameters = /* @__PURE__ */ new Set(); const excludedParameters = /* @__PURE__ */ new Set(); @@ -81935,11 +82143,9 @@ function createTypeChecker(host) { } } function checkClassExpressionExternalHelpers(node) { - if (node.name) - return; + if (node.name) return; const parent = walkUpOuterExpressions(node); - if (!isNamedEvaluationSource(parent)) - return; + if (!isNamedEvaluationSource(parent)) return; const willTransformESDecorators = !legacyDecorators && languageVersion < 99 /* ClassAndClassElementDecorators */; let location; if (willTransformESDecorators && classOrConstructorParameterIsDecorated( @@ -82299,81 +82505,79 @@ function createTypeChecker(host) { var _a, _b, _c, _d, _e; const baseProperties = getPropertiesOfType(baseType); const notImplementedInfo = /* @__PURE__ */ new Map(); - basePropertyCheck: - for (const baseProperty of baseProperties) { - const base = getTargetSymbol(baseProperty); - if (base.flags & 4194304 /* Prototype */) { - continue; + basePropertyCheck: for (const baseProperty of baseProperties) { + const base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + const baseSymbol = getPropertyOfObjectType(type, base.escapedName); + if (!baseSymbol) { + continue; + } + const derived = getTargetSymbol(baseSymbol); + const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived === base) { + const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { + for (const otherBaseType of getBaseTypes(type)) { + if (otherBaseType === baseType) continue; + const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName); + const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); + if (derivedElsewhere && derivedElsewhere !== base) { + continue basePropertyCheck; + } + } + const baseTypeName = typeToString(baseType); + const typeName = typeToString(type); + const basePropertyName = symbolToString(baseProperty); + const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName); + notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties }); } - const baseSymbol = getPropertyOfObjectType(type, base.escapedName); - if (!baseSymbol) { + } else { + const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { continue; } - const derived = getTargetSymbol(baseSymbol); - const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); - Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); - if (derived === base) { - const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { - for (const otherBaseType of getBaseTypes(type)) { - if (otherBaseType === baseType) - continue; - const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName); - const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); - if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; - } - } - const baseTypeName = typeToString(baseType); - const typeName = typeToString(type); - const basePropertyName = symbolToString(baseProperty); - const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName); - notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties }); - } - } else { - const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { + let errorMessage; + const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; + const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; + if (basePropertyFlags && derivedPropertyFlags) { + if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { continue; } - let errorMessage; - const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; - const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; - if (basePropertyFlags && derivedPropertyFlags) { - if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { - continue; - } - const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; - const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; - if (overriddenInstanceProperty || overriddenInstanceAccessor) { - const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); - } else if (useDefineForClassFields) { - const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); - if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { - const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); - const propName = uninitialized.name; - if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); - } + const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); + } else if (useDefineForClassFields) { + const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); + if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { + const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); + const propName = uninitialized.name; + if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { + const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); } } + } + continue; + } else if (isPrototypeProperty(base)) { + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { continue; - } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { - continue; - } else { - Debug.assert(!!(derived.flags & 98304 /* Accessor */)); - errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - } else if (base.flags & 98304 /* Accessor */) { - errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } else { - errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } - error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } else if (base.flags & 98304 /* Accessor */) { + errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; } + error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + } for (const [errorNode, memberInfo] of notImplementedInfo) { if (length(memberInfo.missedProperties) === 1) { if (isClassExpression(errorNode)) { @@ -82508,8 +82712,7 @@ function createTypeChecker(host) { return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { - if (!checkGrammarModifiers(node)) - checkGrammarInterfaceDeclaration(node); + if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); addLazyDiagnostic(() => { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); @@ -82638,11 +82841,10 @@ function createTypeChecker(host) { /*ignoreErrors*/ true ); - if (!symbol) - return evaluatorResult( - /*value*/ - void 0 - ); + if (!symbol) return evaluatorResult( + /*value*/ + void 0 + ); if (expr.kind === 80 /* Identifier */) { const identifier = expr; if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol( @@ -83088,20 +83290,17 @@ function createTypeChecker(host) { return symbol; } const targetSymbol = resolveAlias(symbol); - if (targetSymbol === unknownSymbol) - return targetSymbol; + if (targetSymbol === unknownSymbol) return targetSymbol; while (symbol.flags & 2097152 /* Alias */) { const target = getImmediateAliasedSymbol(symbol); if (target) { - if (target === targetSymbol) - break; + if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { - if (symbol === targetSymbol) - break; + if (symbol === targetSymbol) break; symbol = target; } } @@ -83189,9 +83388,7 @@ function createTypeChecker(host) { checkGrammarModifiers(node); if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (hasSyntacticModifier(node, 32 /* Export */)) { - markExportAsReferenced(node); - } + markLinkedReferences(node, 6 /* ExportImportEquals */); if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { @@ -83289,13 +83486,7 @@ function createTypeChecker(host) { if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { - if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { - markExportAsReferenced(node); - } - const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getSymbolFlags(target) & 111551 /* Value */) { - checkExpressionCached(node.propertyName || node.name); - } + markLinkedReferences(node, 7 /* ExportSpecifier */); } } else { if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && idText(node.propertyName || node.name) === "default") { @@ -83337,8 +83528,8 @@ function createTypeChecker(host) { node )); if (sym) { + markLinkedReferences(node, 3 /* ExportAssignment */); const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, 111551 /* Value */); - markAliasReferenced(sym, id); if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) { @@ -83951,8 +84142,7 @@ function createTypeChecker(host) { } switch (location.kind) { case 307 /* SourceFile */: - if (!isExternalModule(location)) - break; + if (!isExternalModule(location)) break; case 267 /* ModuleDeclaration */: copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */); break; @@ -84029,8 +84219,7 @@ function createTypeChecker(host) { let result; let containingClass = getContainingClass(node); while (containingClass) { - if (result = callback(containingClass)) - break; + if (result = callback(containingClass)) break; containingClass = getContainingClass(containingClass); } return result; @@ -84621,14 +84810,11 @@ function createTypeChecker(host) { return target; } function isArgumentsLocalBinding(nodeIn) { - if (isGeneratedIdentifier(nodeIn)) - return false; + if (isGeneratedIdentifier(nodeIn)) return false; const node = getParseTreeNode(nodeIn, isIdentifier); - if (!node) - return false; + if (!node) return false; const parent = node.parent; - if (!parent) - return false; + if (!parent) return false; const isPropertyName2 = (isPropertyAccessExpression(parent) || isPropertyAssignment(parent)) && parent.name === node; return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol; } @@ -84692,7 +84878,6 @@ function createTypeChecker(host) { if (links.isDeclarationWithCollidingName === void 0) { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) { - const nodeLinks2 = getNodeLinks(symbol.valueDeclaration); if (resolveName( container.parent, symbol.escapedName, @@ -84703,8 +84888,8 @@ function createTypeChecker(host) { false )) { links.isDeclarationWithCollidingName = true; - } else if (nodeLinks2.flags & 16384 /* CapturedBlockScopedBinding */) { - const isDeclaredInLoop = nodeLinks2.flags & 32768 /* BlockScopedBindingInLoop */; + } else if (hasNodeCheckFlag(symbol.valueDeclaration, 16384 /* CapturedBlockScopedBinding */)) { + const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, 32768 /* BlockScopedBindingInLoop */); const inLoopInitializer = isIterationStatement( container, /*lookInLabeledStatements*/ @@ -84786,6 +84971,9 @@ function createTypeChecker(host) { if (!symbol) { return false; } + const container = getSourceFileOfNode(symbol.valueDeclaration); + const fileSymbol = container && getSymbolOfDeclaration(container); + void resolveExternalModuleSymbol(fileSymbol); const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) { return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol); @@ -84820,8 +85008,7 @@ function createTypeChecker(host) { } function isImplementationOfOverload(node) { if (nodeIsPresent(node.body)) { - if (isGetAccessor(node) || isSetAccessor(node)) - return false; + if (isGetAccessor(node) || isSetAccessor(node)) return false; const symbol = getSymbolOfDeclaration(node); const signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node @@ -84835,8 +85022,7 @@ function createTypeChecker(host) { } function declaredParameterTypeContainsUndefined(parameter) { const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter); - if (!typeNode) - return false; + if (!typeNode) return false; const type = getTypeFromTypeNode(typeNode); return containsUndefinedType(type); } @@ -84883,10 +85069,111 @@ function createTypeChecker(host) { function getNodeCheckFlags(node) { var _a; const nodeId = node.id || 0; - if (nodeId < 0 || nodeId >= nodeLinks.length) - return 0; + if (nodeId < 0 || nodeId >= nodeLinks.length) return 0; return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0; } + function hasNodeCheckFlag(node, flag) { + calculateNodeCheckFlagWorker(node, flag); + return !!(getNodeCheckFlags(node) & flag); + } + function calculateNodeCheckFlagWorker(node, flag) { + if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnsotics(getSourceFileOfNode(node), compilerOptions)) { + return; + } + const links = getNodeLinks(node); + if (links.calculatedFlags & flag) { + return; + } + switch (flag) { + case 16 /* SuperInstance */: + case 32 /* SuperStatic */: + return checkSingleSuperExpression(node); + case 128 /* MethodWithSuperPropertyAccessInAsync */: + case 256 /* MethodWithSuperPropertyAssignmentInAsync */: + case 2097152 /* ContainsSuperPropertyInStaticInitializer */: + return checkChildSuperExpressions(node); + case 512 /* CaptureArguments */: + case 8192 /* ContainsCapturedBlockScopeBinding */: + case 65536 /* NeedsLoopOutParameter */: + case 262144 /* ContainsConstructorReference */: + return checkChildIdentifiers(node); + case 536870912 /* ConstructorReference */: + return checkSingleIdentifier(node); + case 4096 /* LoopWithCapturedBlockScopedBinding */: + case 32768 /* BlockScopedBindingInLoop */: + case 16384 /* CapturedBlockScopedBinding */: + return checkContainingBlockScopeBindingUses(node); + default: + return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`); + } + function forEachNodeRecursively(root, cb) { + const rootResult = cb(root, root.parent); + if (rootResult === "skip") return void 0; + if (rootResult) return rootResult; + return forEachChildRecursively(root, cb); + } + function checkSuperExpressions(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */ | 2097152 /* ContainsSuperPropertyInStaticInitializer */; + checkSingleSuperExpression(node2); + return void 0; + } + function checkChildSuperExpressions(node2) { + forEachNodeRecursively(node2, checkSuperExpressions); + } + function checkSingleSuperExpression(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 16 /* SuperInstance */ | 32 /* SuperStatic */; + if (node2.kind === 108 /* SuperKeyword */) { + checkSuperExpression(node2); + } + } + function checkIdentifiers(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 512 /* CaptureArguments */ | 8192 /* ContainsCapturedBlockScopeBinding */ | 65536 /* NeedsLoopOutParameter */ | 262144 /* ContainsConstructorReference */; + checkSingleIdentifier(node2); + return void 0; + } + function checkChildIdentifiers(node2) { + forEachNodeRecursively(node2, checkIdentifiers); + } + function checkSingleIdentifier(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */ | 16384 /* CapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */; + if (isIdentifier(node2) && isExpressionNode(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) { + const s = getSymbolAtLocation( + node2, + /*ignoreErrors*/ + true + ); + if (s && s !== unknownSymbol) { + checkIdentifierCalculateNodeCheckFlags(node2, s); + } + } + } + function checkBlockScopeBindings(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 4096 /* LoopWithCapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */; + checkSingleBlockScopeBinding(node2); + return void 0; + } + function checkContainingBlockScopeBindingUses(node2) { + const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2); + forEachNodeRecursively(scope, checkBlockScopeBindings); + } + function checkSingleBlockScopeBinding(node2) { + checkSingleIdentifier(node2); + if (isComputedPropertyName(node2)) { + checkComputedPropertyName(node2); + } + if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) { + setNodeLinksForPrivateIdentifierScope(node2.parent); + } + } + } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); return getNodeLinks(node).enumMemberValue ?? evaluatorResult( @@ -84907,7 +85194,15 @@ function createTypeChecker(host) { if (node.kind === 306 /* EnumMember */) { return getEnumMemberValue(node).value; } - const symbol = getNodeLinks(node).resolvedSymbol; + if (!getNodeLinks(node).resolvedSymbol) { + void checkExpressionCached(node); + } + const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName( + node, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) : void 0); if (symbol && symbol.flags & 8 /* EnumMember */) { const member = symbol.valueDeclaration; if (isEnumConst(member.parent)) { @@ -84922,12 +85217,10 @@ function createTypeChecker(host) { function getTypeReferenceSerializationKind(typeNameIn, location) { var _a; const typeName = getParseTreeNode(typeNameIn, isEntityName); - if (!typeName) - return 0 /* Unknown */; + if (!typeName) return 0 /* Unknown */; if (location) { location = getParseTreeNode(location); - if (!location) - return 0 /* Unknown */; + if (!location) return 0 /* Unknown */; } let isTypeOnly = false; if (isQualifiedName(typeName)) { @@ -85042,6 +85335,7 @@ function createTypeChecker(host) { function getSingleReturnExpression(declaration) { let candidateExpr; if (declaration && !nodeIsMissing(declaration.body)) { + if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; const body = declaration.body; if (body && isBlock(body)) { forEachReturnStatement(body, (s) => { @@ -85176,22 +85470,6 @@ function createTypeChecker(host) { } return false; } - function isNonNarrowedBindableName(node) { - if (!hasBindableName(node.parent)) { - return false; - } - const expression = node.expression; - if (!isEntityNameExpression(expression)) { - return true; - } - const type = getTypeOfExpression(expression); - const symbol = getSymbolAtLocation(expression); - if (!symbol) { - return false; - } - const declaredType = getTypeOfSymbol(symbol); - return declaredType === type; - } function literalTypeToNode(type, enclosing, tracker) { const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression( type.symbol, @@ -85201,8 +85479,7 @@ function createTypeChecker(host) { void 0, tracker ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); - if (enumResult) - return enumResult; + if (enumResult) return enumResult; const literalValue = type.value; return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue); } @@ -85276,9 +85553,10 @@ function createTypeChecker(host) { const node = getParseTreeNode(nodeIn); return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true; }, - getNodeCheckFlags: (nodeIn) => { + hasNodeCheckFlag: (nodeIn, flag) => { const node = getParseTreeNode(nodeIn); - return node ? getNodeCheckFlags(node) : 0; + if (!node) return false; + return hasNodeCheckFlag(node, flag); }, isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible, @@ -85301,6 +85579,10 @@ function createTypeChecker(host) { return node ? getEnumMemberValue(node) : void 0; }, collectLinkedAliases, + markLinkedReferences: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node && markLinkedReferences(node, 0 /* Unspecified */); + }, getReferencedValueDeclaration, getReferencedValueDeclarations, getTypeReferenceSerializationKind, @@ -85311,7 +85593,6 @@ function createTypeChecker(host) { return node && getExternalModuleFileFromDeclaration(node); }, isLiteralConstDeclaration, - isNonNarrowedBindableName, isLateBound: (nodeIn) => { const node = getParseTreeNode(nodeIn, isDeclaration); const symbol = node && getSymbolOfDeclaration(node); @@ -85331,19 +85612,17 @@ function createTypeChecker(host) { if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker); } + resolveExternalModuleSymbol(sym); return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker); }, isImportRequiredByAugmentation }; function isImportRequiredByAugmentation(node) { const file = getSourceFileOfNode(node); - if (!file.symbol) - return false; + if (!file.symbol) return false; const importTarget = getExternalModuleFileFromDeclaration(node); - if (!importTarget) - return false; - if (importTarget === file) - return false; + if (!importTarget) return false; + if (importTarget === file) return false; const exports2 = getExportsOfModule(file.symbol); for (const s of arrayFrom(exports2.values())) { if (s.mergeId) { @@ -85414,8 +85693,7 @@ function createTypeChecker(host) { if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (!isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (!isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } @@ -85520,8 +85798,7 @@ function createTypeChecker(host) { if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } @@ -85552,39 +85829,40 @@ function createTypeChecker(host) { amalgamatedDuplicates = void 0; } function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + if (compilerOptions.importHelpers) { const sourceFile = getSourceFileOfNode(location); if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */)) { const helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { - const uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) { - if (uncheckedHelpers & helper) { - for (const name of getHelperNames(helper)) { - if (requestedExternalEmitHelperNames.has(name)) - continue; - requestedExternalEmitHelperNames.add(name); - const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */)); - if (!symbol) { - error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); - } else if (helper & 524288 /* ClassPrivateFieldGet */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) { - error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); - } - } else if (helper & 1048576 /* ClassPrivateFieldSet */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) { - error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); - } - } else if (helper & 1024 /* SpreadArray */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) { - error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + const links = getSymbolLinks(helpersModule); + links.requestedExternalEmitHelpers ?? (links.requestedExternalEmitHelpers = 0); + if ((links.requestedExternalEmitHelpers & helpers) !== helpers) { + const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers; + for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + for (const name of getHelperNames(helper)) { + const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */)); + if (!symbol) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); + } else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); + } + } else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); + } + } else if (helper & 1024 /* SpreadArray */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) { + error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + } } } } } } + links.requestedExternalEmitHelpers |= helpers; } - requestedExternalEmitHelpers |= helpers; } } } @@ -85644,11 +85922,12 @@ function createTypeChecker(host) { return Debug.fail("Unrecognized helper"); } } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + function resolveHelpersModule(file, errorNode) { + const links = getNodeLinks(file); + if (!links.externalHelpersModule) { + links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; } - return externalHelpersModule; + return links.externalHelpersModule; } function checkGrammarModifiers(node) { var _a; @@ -85967,8 +86246,7 @@ function createTypeChecker(host) { return false; } function reportObviousModifierErrors(node) { - if (!node.modifiers) - return false; + if (!node.modifiers) return false; const modifier = findFirstIllegalModifier(node); return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here); } @@ -86442,7 +86720,6 @@ function createTypeChecker(host) { return true; } } - return false; } } if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 65536 /* AwaitContext */) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { @@ -87152,6 +87429,20 @@ function createTypeChecker(host) { const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */; return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */; } + function getJSXRuntimeImportSpecifier(file, specifierText) { + const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0; + const specifier = file == null ? void 0 : file.imports[jsxImportIndex]; + if (specifier) { + Debug.assert(nodeIsSynthesized(specifier) && specifier.text === specifierText, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`); + } + return specifier; + } + function getImportHelpersImportSpecifier(file) { + Debug.assert(compilerOptions.importHelpers, "Expected importHelpers to be enabled"); + const specifier = file.imports[0]; + Debug.assert(specifier && nodeIsSynthesized(specifier) && specifier.text === "tslib", `Expected sourceFile.imports[0] to be the synthesized tslib import`); + return specifier; + } } function isNotAccessor(declaration) { return !isAccessor(declaration); @@ -87238,8 +87529,7 @@ var SymbolTrackerImpl = class _SymbolTrackerImpl { this.onDiagnosticReported(); return true; } - if (!(symbol.flags & 262144 /* TypeParameter */)) - ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); + if (!(symbol.flags & 262144 /* TypeParameter */)) ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); } return false; } @@ -87405,8 +87695,7 @@ function visitArrayWorker(nodes, visitor, test, start, count) { function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor = visitNodes2) { context.startLexicalEnvironment(); statements = nodesVisitor(statements, visitor, isStatement, start); - if (ensureUseStrict) - statements = context.factory.ensureUseStrict(statements); + if (ensureUseStrict) statements = context.factory.ensureUseStrict(statements); return factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } function visitParameterList(nodes, visitor, context, nodesVisitor = visitNodes2) { @@ -87429,8 +87718,7 @@ function addDefaultValueAssignmentsIfNeeded(parameters, context) { const parameter = parameters[i]; const updated = addDefaultValueAssignmentIfNeeded(parameter, context); if (result || updated !== parameter) { - if (!result) - result = parameters.slice(0, i); + if (!result) result = parameters.slice(0, i); result[i] = updated; } } @@ -88666,8 +88954,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, function setSourceContent(sourceIndex, content) { enter(); if (content !== null) { - if (!sourcesContent) - sourcesContent = []; + if (!sourcesContent) sourcesContent = []; while (sourcesContent.length < sourceIndex) { sourcesContent.push(null); } @@ -88677,8 +88964,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, } function addName(name) { enter(); - if (!nameToNameIndexMap) - nameToNameIndexMap = /* @__PURE__ */ new Map(); + if (!nameToNameIndexMap) nameToNameIndexMap = /* @__PURE__ */ new Map(); let nameIndex = nameToNameIndexMap.get(name); if (nameIndex === void 0) { nameIndex = names.length; @@ -88753,8 +89039,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, newSourceLine = raw.sourceLine; newSourceCharacter = raw.sourceCharacter; if (map2.names && raw.nameIndex !== void 0) { - if (!nameIndexToNewNameIndexMap) - nameIndexToNewNameIndexMap = []; + if (!nameIndexToNewNameIndexMap) nameIndexToNewNameIndexMap = []; newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; if (newNameIndex === void 0) { nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map2.names[raw.nameIndex]); @@ -88891,40 +89176,27 @@ function decodeMappings(mappings) { let hasSource = false; let hasName = false; generatedCharacter += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (generatedCharacter < 0) - return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (hasReportedError()) return stopIterating(); + if (generatedCharacter < 0) return setErrorAndStopIterating("Invalid generatedCharacter found"); if (!isSourceMappingSegmentEnd()) { hasSource = true; sourceIndex += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceIndex < 0) - return setErrorAndStopIterating("Invalid sourceIndex found"); - if (isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + if (hasReportedError()) return stopIterating(); + if (sourceIndex < 0) return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); sourceLine += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceLine < 0) - return setErrorAndStopIterating("Invalid sourceLine found"); - if (isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + if (hasReportedError()) return stopIterating(); + if (sourceLine < 0) return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); sourceCharacter += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceCharacter < 0) - return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (hasReportedError()) return stopIterating(); + if (sourceCharacter < 0) return setErrorAndStopIterating("Invalid sourceCharacter found"); if (!isSourceMappingSegmentEnd()) { hasName = true; nameIndex += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (nameIndex < 0) - return setErrorAndStopIterating("Invalid nameIndex found"); - if (!isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + if (hasReportedError()) return stopIterating(); + if (nameIndex < 0) return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); } } return { value: captureMapping(hasSource, hasName), done }; @@ -88969,11 +89241,9 @@ function decodeMappings(mappings) { let shiftCount = 0; let value = 0; for (; moreDigits; pos++) { - if (pos >= mappings.length) - return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + if (pos >= mappings.length) return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; const currentByte = base64FormatDecode(mappings.charCodeAt(pos)); - if (currentByte === -1) - return setError("Invalid character in VLQ"), -1; + if (currentByte === -1) return setError("Invalid character in VLQ"), -1; moreDigits = (currentByte & 32) !== 0; value = value | (currentByte & 31) << shiftCount; shiftCount += 5; @@ -89000,10 +89270,8 @@ function getOriginalNodeId(node) { return node ? getNodeId(node) : 0; } function containsDefaultReference(node) { - if (!node) - return false; - if (!isNamedImports(node) && !isNamedExports(node)) - return false; + if (!node) return false; + if (!isNamedImports(node) && !isNamedExports(node)) return false; return some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { @@ -89029,8 +89297,7 @@ function getImportNeedsImportStarHelper(node) { if (!bindings) { return false; } - if (!isNamedImports(bindings)) - return false; + if (!isNamedImports(bindings)) return false; let defaultRefCount = 0; for (const binding of bindings.elements) { if (isNamedDefaultReference(binding)) { @@ -89049,8 +89316,8 @@ function collectExternalModuleInfo(context, sourceFile) { const exportSpecifiers = new IdentifierNameMultiMap(); const exportedBindings = []; const uniqueExports = /* @__PURE__ */ new Map(); + const exportedFunctions = /* @__PURE__ */ new Set(); let exportedNames; - let exportedFunctions; let hasExportDefault = false; let exportEquals; let hasExportStarsToExportValues = false; @@ -89110,19 +89377,12 @@ function collectExternalModuleInfo(context, sourceFile) { break; case 262 /* FunctionDeclaration */: if (hasSyntacticModifier(node, 32 /* Export */)) { - exportedFunctions = append(exportedFunctions, node); - if (hasSyntacticModifier(node, 2048 /* Default */)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); - hasExportDefault = true; - } - } else { - const name = node.name; - if (!uniqueExports.get(idText(name))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(idText(name), true); - } - } + addExportedFunctionDeclaration( + node, + /*name*/ + void 0, + hasSyntacticModifier(node, 2048 /* Default */) + ); } break; case 263 /* ClassDeclaration */: @@ -89158,6 +89418,10 @@ function collectExternalModuleInfo(context, sourceFile) { } const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { + if (decl.kind === 262 /* FunctionDeclaration */) { + addExportedFunctionDeclaration(decl, specifier.name, specifier.name.escapedText === "default" /* Default */); + continue; + } multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } uniqueExports.set(idText(specifier.name), true); @@ -89165,6 +89429,21 @@ function collectExternalModuleInfo(context, sourceFile) { } } } + function addExportedFunctionDeclaration(node, name, isDefault) { + exportedFunctions.add(node); + if (isDefault) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name ?? context.factory.getDeclarationName(node)); + hasExportDefault = true; + } + } else { + name ?? (name = node.name); + if (!uniqueExports.get(idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(idText(name), true); + } + } + } } function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { @@ -89450,8 +89729,7 @@ function getAllDecoratorsOfProperty(property) { function walkUpLexicalEnvironments(env, cb) { while (env) { const result = cb(env); - if (result !== void 0) - return result; + if (result !== void 0) return result; env = env.previous; } } @@ -89835,16 +90113,12 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, } function isSimpleBindingOrAssignmentElement(element) { const target = getTargetOfBindingOrAssignmentElement(element); - if (!target || isOmittedExpression(target)) - return true; + if (!target || isOmittedExpression(target)) return true; const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); - if (propertyName && !isPropertyNameLiteral(propertyName)) - return false; + if (propertyName && !isPropertyNameLiteral(propertyName)) return false; const initializer = getInitializerOfBindingOrAssignmentElement(element); - if (initializer && !isSimpleInlineableExpression(initializer)) - return false; - if (isBindingOrAssignmentPattern(target)) - return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); + if (initializer && !isSimpleInlineableExpression(initializer)) return false; + if (isBindingOrAssignmentPattern(target)) return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); return isIdentifier(target); } function createDefaultValueCheck(flattenContext, value, defaultValue, location) { @@ -90504,8 +90778,7 @@ function transformTypeScript(context) { return isModifier(node) ? void 0 : visitor(node); } function modifierVisitor(node) { - if (isDecorator(node)) - return void 0; + if (isDecorator(node)) return void 0; if (modifierToFlag(node.kind) & 28895 /* TypeScriptModifier */) { return void 0; } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) { @@ -90653,21 +90926,14 @@ function transformTypeScript(context) { true, /*isStatic*/ true - ))) - facts |= 1 /* HasStaticInitializedProperties */; + ))) facts |= 1 /* HasStaticInitializedProperties */; const extendsClauseElement = getEffectiveBaseTypeNode(node); - if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */) - facts |= 64 /* IsDerivedClass */; - if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) - facts |= 2 /* HasClassOrConstructorParameterDecorators */; - if (childIsDecorated(legacyDecorators, node)) - facts |= 4 /* HasMemberDecorators */; - if (isExportOfNamespace(node)) - facts |= 8 /* IsExportOfNamespace */; - else if (isDefaultExternalModuleExport(node)) - facts |= 32 /* IsDefaultExternalExport */; - else if (isNamedExternalModuleExport(node)) - facts |= 16 /* IsNamedExternalExport */; + if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; + if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) facts |= 2 /* HasClassOrConstructorParameterDecorators */; + if (childIsDecorated(legacyDecorators, node)) facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) facts |= 16 /* IsNamedExternalExport */; return facts; } function hasTypeScriptClassSyntax(node) { @@ -90864,8 +91130,7 @@ function transformTypeScript(context) { return modifiers; } function getTypeMetadata(node, container) { - if (!legacyDecorators) - return void 0; + if (!legacyDecorators) return void 0; return USE_NEW_TYPE_METADATA_FORMAT ? getNewTypeMetadata(node, container) : getOldTypeMetadata(node, container); } function getOldTypeMetadata(node, container) { @@ -92430,10 +92695,8 @@ function transformClassFields(context) { return fallbackVisitor(node); } function shouldTransformClassElementToWeakMap(node) { - if (shouldTransformPrivateElementsOrClassStaticBlocks) - return true; - if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) - return true; + if (shouldTransformPrivateElementsOrClassStaticBlocks) return true; + if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) return true; return false; } function visitMethodOrAccessorDeclaration(node) { @@ -92493,10 +92756,9 @@ function transformClassFields(context) { } } } - function getClassThis() { + function tryGetClassThis() { const lex = getClassLexicalEnvironment(); - const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); - return Debug.checkDefined(classThis); + return lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); @@ -92524,7 +92786,7 @@ function transformClassFields(context) { setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const receiver = isStatic(node) ? tryGetClassThis() ?? factory2.createThis() : factory2.createThis(); const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); @@ -93090,7 +93352,7 @@ function transformClassFields(context) { var _a; let facts = 0 /* None */; const original = getOriginalNode(node); - if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + if (isClassLike(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { facts |= 1 /* ClassWasDecorated */; } if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { @@ -93126,7 +93388,7 @@ function transformClassFields(context) { containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; - if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + if (resolver.hasNodeCheckFlag(member, 262144 /* ContainsConstructorReference */)) { facts |= 2 /* NeedsClassConstructorReference */; } } else if (isPropertyDeclaration(member)) { @@ -93233,7 +93495,7 @@ function transformClassFields(context) { if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { getClassLexicalEnvironment().classThis = node.emitNode.classThis; } - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); const isExport = hasSyntacticModifier(node, 32 /* Export */); const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -93295,15 +93557,14 @@ function transformClassFields(context) { var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const classCheckFlags = resolver.getNodeCheckFlags(node); - const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); + const requiresBlockScopedVar = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, /*reservedInNestedScopes*/ @@ -93871,7 +94132,7 @@ function transformClassFields(context) { const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { const generatedName = factory2.getGeneratedNameForNode(name); - if (resolver.getNodeCheckFlags(name) & 32768 /* BlockScopedBindingInLoop */) { + if (resolver.hasNodeCheckFlag(name, 32768 /* BlockScopedBindingInLoop */)) { addBlockScopedVariable(generatedName); } else { hoistVariableDeclaration(generatedName); @@ -94025,7 +94286,7 @@ function transformClassFields(context) { prefix, suffix ); - if (resolver.getNodeCheckFlags(node) & 32768 /* BlockScopedBindingInLoop */) { + if (resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */)) { addBlockScopedVariable(identifier); } else { hoistVariableDeclaration(identifier); @@ -94120,10 +94381,8 @@ function transformClassFields(context) { } function visitArrayAssignmentElement(node) { if (isArrayBindingOrAssignmentElement(node)) { - if (isSpreadElement(node)) - return visitAssignmentRestElement(node); - if (!isOmittedExpression(node)) - return visitAssignmentElement(node); + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); } return visitEachChild(node, visitor, context); } @@ -94158,12 +94417,9 @@ function transformClassFields(context) { } function visitObjectAssignmentElement(node) { Debug.assertNode(node, isObjectBindingOrAssignmentElement); - if (isSpreadAssignment(node)) - return visitAssignmentRestProperty(node); - if (isShorthandPropertyAssignment(node)) - return visitShorthandAssignmentProperty(node); - if (isPropertyAssignment(node)) - return visitAssignmentProperty(node); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); return visitEachChild(node, visitor, context); } function visitAssignmentPattern(node) { @@ -94269,7 +94525,7 @@ function transformClassFields(context) { } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -94522,13 +94778,11 @@ function createRuntimeTypeSerializer(context) { for (let typeNode of types) { typeNode = skipTypeParentheses(typeNode); if (typeNode.kind === 146 /* NeverKeyword */) { - if (isIntersection) - return factory2.createVoidZero(); + if (isIntersection) return factory2.createVoidZero(); continue; } if (typeNode.kind === 159 /* UnknownKeyword */) { - if (!isIntersection) - return factory2.createIdentifier("Object"); + if (!isIntersection) return factory2.createIdentifier("Object"); continue; } if (typeNode.kind === 133 /* AnyKeyword */) { @@ -94752,18 +95006,15 @@ function transformLegacyDecorators(context) { } function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { for (const member of node.members) { - if (!canHaveDecorators(member)) - continue; + if (!canHaveDecorators(member)) continue; const allDecorators = getAllDecoratorsOfClassElement( member, node, /*useLegacyDecorators*/ true ); - if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) - return true; - if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) - return true; + if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) return true; + if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) return true; } return false; } @@ -95141,7 +95392,7 @@ function transformLegacyDecorators(context) { } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */)) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -95174,7 +95425,7 @@ function transformLegacyDecorators(context) { } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -95460,14 +95711,10 @@ function transformESDecorators(context) { } function getHelperVariableName(node) { let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, 99 /* ESNext */) ? node.name.text : isClassLike(node) ? "class" : "member"; - if (isGetAccessor(node)) - declarationName = `get_${declarationName}`; - if (isSetAccessor(node)) - declarationName = `set_${declarationName}`; - if (node.name && isPrivateIdentifier(node.name)) - declarationName = `private_${declarationName}`; - if (isStatic(node)) - declarationName = `static_${declarationName}`; + if (isGetAccessor(node)) declarationName = `get_${declarationName}`; + if (isSetAccessor(node)) declarationName = `set_${declarationName}`; + if (node.name && isPrivateIdentifier(node.name)) declarationName = `private_${declarationName}`; + if (isStatic(node)) declarationName = `static_${declarationName}`; return "_" + declarationName; } function createHelperVariable(node, suffix) { @@ -96690,10 +96937,8 @@ function transformESDecorators(context) { } function visitArrayAssignmentElement(node) { Debug.assertNode(node, isArrayBindingOrAssignmentElement); - if (isSpreadElement(node)) - return visitAssignmentRestElement(node); - if (!isOmittedExpression(node)) - return visitAssignmentElement(node); + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); return visitEachChild(node, visitor, context); } function visitAssignmentProperty(node) { @@ -96727,12 +96972,9 @@ function transformESDecorators(context) { } function visitObjectAssignmentElement(node) { Debug.assertNode(node, isObjectBindingOrAssignmentElement); - if (isSpreadAssignment(node)) - return visitAssignmentRestProperty(node); - if (isShorthandPropertyAssignment(node)) - return visitShorthandAssignmentProperty(node); - if (isPropertyAssignment(node)) - return visitAssignmentProperty(node); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); return visitEachChild(node, visitor, context); } function visitAssignmentPattern(node) { @@ -97492,7 +97734,7 @@ function transformES2017(context) { hasSuperElementAccess = false; let updated = visitFunctionBody(node.body, visitor, context); const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */; + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */; if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -97503,9 +97745,9 @@ function transformES2017(context) { updated = factory2.updateBlock(updated, statements); } if (hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(updated, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(updated, asyncSuperHelper); } } @@ -97572,7 +97814,7 @@ function transformES2017(context) { const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0; const isArrowFunction2 = node.kind === 219 /* ArrowFunction */; const savedLexicalArgumentsBinding = lexicalArgumentsBinding; - const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 512 /* CaptureArguments */) !== 0; + const hasLexicalArguments = resolver.hasNodeCheckFlag(node, 512 /* CaptureArguments */); const captureLexicalArguments = hasLexicalArguments && !lexicalArgumentsBinding; if (captureLexicalArguments) { lexicalArgumentsBinding = factory2.createUniqueName("arguments"); @@ -97627,7 +97869,7 @@ function transformES2017(context) { ) ) ); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -97646,9 +97888,9 @@ function transformES2017(context) { ); setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(block, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(block, asyncSuperHelper); } } @@ -97707,7 +97949,7 @@ function transformES2017(context) { } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -97811,7 +98053,7 @@ function transformES2017(context) { } } function createSuperAccessVariableStatement(factory2, resolver, node, names) { - const hasBinding = (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) !== 0; + const hasBinding = resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */); const accessors = []; names.forEach((_, key) => { const name = unescapeLeadingUnderscores(key); @@ -98906,7 +99148,7 @@ function transformES2018(context) { !!(hierarchyFacts & 1 /* HasLexicalThis */) ) ); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties); @@ -98916,9 +99158,9 @@ function transformES2018(context) { outerStatements.push(returnStatement); const block = factory2.updateBlock(node.body, outerStatements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(block, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(block, asyncSuperHelper); } } @@ -99051,7 +99293,7 @@ function transformES2018(context) { } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -99682,10 +99924,10 @@ function transformESNext(context) { function visitForOfStatement(node) { if (isUsingVariableDeclarationList(node.initializer)) { const forInitializer = node.initializer; - Debug.assertNode(forInitializer, isUsingVariableDeclarationList); - Debug.assert(forInitializer.declarations.length === 1, "ForInitializer may only have one declaration"); - const forDecl = forInitializer.declarations[0]; - Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); + const forDecl = firstOrUndefined(forInitializer.declarations) || factory2.createVariableDeclaration(factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + )); const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */; const temp = factory2.getGeneratedNameForNode(forDecl.name); const usingVar = factory2.updateVariableDeclaration( @@ -99840,8 +100082,7 @@ function transformESNext(context) { append(statements, hoist(node)); } function hoist(node) { - if (!topLevelStatements) - return node; + if (!topLevelStatements) return node; switch (node.kind) { case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: @@ -100144,10 +100385,8 @@ function getUsingKindOfStatements(statements) { let result = 0 /* None */; for (const statement of statements) { const usingKind = getUsingKind(statement); - if (usingKind === 2 /* Async */) - return 2 /* Async */; - if (usingKind > result) - result = usingKind; + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; } return result; } @@ -100155,10 +100394,8 @@ function getUsingKindOfCaseOrDefaultClauses(clauses) { let result = 0 /* None */; for (const clause of clauses) { const usingKind = getUsingKindOfStatements(clause.statements); - if (usingKind === 2 /* Async */) - return 2 /* Async */; - if (usingKind > result) - result = usingKind; + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; } return result; } @@ -101661,8 +101898,7 @@ function transformES2015(context) { } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */; - if (!constructor) - return createDefaultConstructorBody(node, isDerivedClass); + if (!constructor) return createDefaultConstructorBody(node, isDerivedClass); const prologue = []; const statements = []; resumeLexicalEnvironment(); @@ -102762,9 +102998,8 @@ function transformES2015(context) { return createRange(pos, end); } function shouldEmitExplicitInitializerForLetDeclaration(node) { - const flags = resolver.getNodeCheckFlags(node); - const isCapturedInFunction = flags & 16384 /* CapturedBlockScopedBinding */; - const isDeclaredInLoop = flags & 32768 /* BlockScopedBindingInLoop */; + const isCapturedInFunction = resolver.hasNodeCheckFlag(node, 16384 /* CapturedBlockScopedBinding */); + const isDeclaredInLoop = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); const emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || isCapturedInFunction && isDeclaredInLoop && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0; const emitExplicitInitializer = !emittedAsTopLevel && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0 && (!resolver.isDeclarationWithCollidingName(node) || isDeclaredInLoop && !isCapturedInFunction && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0); return emitExplicitInitializer; @@ -103215,7 +103450,7 @@ function transformES2015(context) { return factory2.inlineExpressions(expressions); } function shouldConvertPartOfIterationStatement(node) { - return (resolver.getNodeCheckFlags(node) & 8192 /* ContainsCapturedBlockScopeBinding */) !== 0; + return resolver.hasNodeCheckFlag(node, 8192 /* ContainsCapturedBlockScopeBinding */); } function shouldConvertInitializerOfForStatement(node) { return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); @@ -103230,7 +103465,7 @@ function transformES2015(context) { return shouldConvertBodyOfIterationStatement(node) || shouldConvertInitializerOfForStatement(node); } function shouldConvertBodyOfIterationStatement(node) { - return (resolver.getNodeCheckFlags(node) & 4096 /* LoopWithCapturedBlockScopedBinding */) !== 0; + return resolver.hasNodeCheckFlag(node, 4096 /* LoopWithCapturedBlockScopedBinding */); } function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { if (!state.hoistedLocalVariables) { @@ -103279,10 +103514,8 @@ function transformES2015(context) { const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : void 0; const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : void 0; convertedLoopState = outerConvertedLoopState; - if (initializerFunction) - statements.push(initializerFunction.functionDeclaration); - if (bodyFunction) - statements.push(bodyFunction.functionDeclaration); + if (initializerFunction) statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) statements.push(bodyFunction.functionDeclaration); addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); if (initializerFunction) { statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); @@ -103488,10 +103721,8 @@ function transformES2015(context) { const functionName = factory2.createUniqueName("_loop_init"); const containsYield = (node.initializer.transformFlags & 1048576 /* ContainsYield */) !== 0; let emitFlags = 0 /* None */; - if (currentState.containsLexicalThis) - emitFlags |= 16 /* CapturesThis */; - if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) - emitFlags |= 524288 /* AsyncFunctionBody */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) emitFlags |= 524288 /* AsyncFunctionBody */; const statements = []; statements.push(factory2.createVariableStatement( /*modifiers*/ @@ -103583,14 +103814,11 @@ function transformES2015(context) { /*multiLine*/ true ); - if (isBlock(statement)) - setOriginalNode(loopBody, statement); + if (isBlock(statement)) setOriginalNode(loopBody, statement); const containsYield = (node.statement.transformFlags & 1048576 /* ContainsYield */) !== 0; let emitFlags = 1048576 /* ReuseTempVariableScope */; - if (currentState.containsLexicalThis) - emitFlags |= 16 /* CapturesThis */; - if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) - emitFlags |= 524288 /* AsyncFunctionBody */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) emitFlags |= 524288 /* AsyncFunctionBody */; const functionDeclaration = factory2.createVariableStatement( /*modifiers*/ void 0, @@ -103786,11 +104014,11 @@ function transformES2015(context) { void 0, name )); - const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + const needsOutParam = resolver.hasNodeCheckFlag(decl, 65536 /* NeedsLoopOutParameter */); + if (needsOutParam || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 65536 /* NeedsLoopOutParameter */) { + if (needsOutParam) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -105662,8 +105890,7 @@ function transformGenerators(context) { } function endBlock() { const block = peekBlock(); - if (block === void 0) - return Debug.fail("beginBlock was never called."); + if (block === void 0) return Debug.fail("beginBlock was never called."); const index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -106497,10 +106724,8 @@ function transformModule(context) { ); } } - if (some(currentModuleInfo.exportedFunctions)) { - for (const f of currentModuleInfo.exportedFunctions) { - appendExportsOfHoistedDeclaration(statements, f); - } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); } append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); @@ -106817,10 +107042,8 @@ function transformModule(context) { if (some(currentModuleInfo.exportedNames)) { append(statements, factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero()))); } - if (some(currentModuleInfo.exportedFunctions)) { - for (const f of currentModuleInfo.exportedFunctions) { - appendExportsOfHoistedDeclaration(statements, f); - } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); } append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); if (moduleKind === 2 /* AMD */) { @@ -108534,7 +108757,7 @@ function transformSystemModule(context) { if (!moduleInfo.hasExportStarsToExportValues) { return; } - if (!some(moduleInfo.exportedNames) && !some(moduleInfo.exportedFunctions) && moduleInfo.exportSpecifiers.size === 0) { + if (!some(moduleInfo.exportedNames) && moduleInfo.exportedFunctions.size === 0 && moduleInfo.exportSpecifiers.size === 0) { let hasExportDeclarationWithExportClause = false; for (const externalImport of moduleInfo.externalImports) { if (externalImport.kind === 278 /* ExportDeclaration */ && externalImport.exportClause) { @@ -108565,19 +108788,17 @@ function transformSystemModule(context) { ); } } - if (moduleInfo.exportedFunctions) { - for (const f of moduleInfo.exportedFunctions) { - if (hasSyntacticModifier(f, 2048 /* Default */)) { - continue; - } - Debug.assert(!!f.name); - exportedNames.push( - factory2.createPropertyAssignment( - factory2.createStringLiteralFromNode(f.name), - factory2.createTrue() - ) - ); + for (const f of moduleInfo.exportedFunctions) { + if (hasSyntacticModifier(f, 2048 /* Default */)) { + continue; } + Debug.assert(!!f.name); + exportedNames.push( + factory2.createPropertyAssignment( + factory2.createStringLiteralFromNode(f.name), + factory2.createTrue() + ) + ); } const exportedNamesStorageRef = factory2.createUniqueName("exportedNames"); statements.push( @@ -109634,24 +109855,20 @@ function transformSystemModule(context) { function getReferencedDeclaration(name) { if (!isGeneratedIdentifier(name)) { const importDeclaration = resolver.getReferencedImportDeclaration(name); - if (importDeclaration) - return importDeclaration; + if (importDeclaration) return importDeclaration; const valueDeclaration = resolver.getReferencedValueDeclaration(name); - if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) - return valueDeclaration; + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) return valueDeclaration; const declarations = resolver.getReferencedValueDeclarations(name); if (declarations) { for (const declaration of declarations) { - if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) - return declaration; + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) return declaration; } } return valueDeclaration; } } function preventSubstitution(node) { - if (noSubstitution === void 0) - noSubstitution = []; + if (noSubstitution === void 0) noSubstitution = []; noSubstitution[getNodeId(node)] = true; return node; } @@ -110300,7 +110517,7 @@ function createGetIsolatedDeclarationErrors(resolver) { [260 /* VariableDeclaration */]: Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [172 /* PropertyDeclaration */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [171 /* PropertySignature */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, - [167 /* ComputedPropertyName */]: Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations, + [167 /* ComputedPropertyName */]: Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations, [305 /* SpreadAssignment */]: Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations, [304 /* ShorthandPropertyAssignment */]: Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations, [209 /* ArrayLiteralExpression */]: Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations, @@ -110313,6 +110530,9 @@ function createGetIsolatedDeclarationErrors(resolver) { if (heritageClause) { return createDiagnosticForNode(node, Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations); } + if ((isPartOfTypeNode(node) || isTypeQueryNode(node.parent)) && (isEntityName(node) || isEntityNameExpression(node))) { + return createEntityInTypeNodeError(node); + } Debug.type(node); switch (node.kind) { case 177 /* GetAccessor */: @@ -110348,8 +110568,13 @@ function createGetIsolatedDeclarationErrors(resolver) { } } function findNearestDeclaration(node) { - const result = findAncestor(node, (n) => isExportAssignment(n) || (isStatement(n) ? "quit" : isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n))); - return result; + const result = findAncestor(node, (n) => isExportAssignment(n) || isStatement(n) || isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n)); + if (!result) return void 0; + if (isExportAssignment(result)) return result; + if (isReturnStatement(result)) { + return findAncestor(result, (n) => isFunctionLikeDeclaration(n) && !isConstructorDeclaration(n)); + } + return isStatement(result) ? void 0 : result; } function createAccessorTypeError(node) { const { getAccessor, setAccessor } = getAllAccessorDeclarations(node.symbol.declarations, node); @@ -110363,11 +110588,10 @@ function createGetIsolatedDeclarationErrors(resolver) { } return diag2; } - function createObjectLiteralError(node) { - const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + function addParentDeclarationRelatedInfo(node, diag2) { const parentDeclaration = findNearestDeclaration(node); if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( parentDeclaration.name, /*includeTrivia*/ false @@ -110376,30 +110600,19 @@ function createGetIsolatedDeclarationErrors(resolver) { } return diag2; } + function createObjectLiteralError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } function createArrayLiteralError(node) { const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); - const parentDeclaration = findNearestDeclaration(node); - if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( - parentDeclaration.name, - /*includeTrivia*/ - false - ); - addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); - } + addParentDeclarationRelatedInfo(node, diag2); return diag2; } function createReturnTypeError(node) { const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); - const parentDeclaration = findNearestDeclaration(node); - if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( - parentDeclaration.name, - /*includeTrivia*/ - false - ); - addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); - } + addParentDeclarationRelatedInfo(node, diag2); addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind])); return diag2; } @@ -110437,11 +110650,20 @@ function createGetIsolatedDeclarationErrors(resolver) { function createClassExpressionError(node) { return createExpressionError(node, Diagnostics.Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations); } + function createEntityInTypeNodeError(node) { + const diag2 = createDiagnosticForNode(node, Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations, getTextOfNode( + node, + /*includeTrivia*/ + false + )); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } function createExpressionError(node, diagnosticMessage) { const parentDeclaration = findNearestDeclaration(node); let diag2; if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( parentDeclaration.name, /*includeTrivia*/ false @@ -110465,19 +110687,20 @@ function createGetIsolatedDeclarationErrors(resolver) { // src/compiler/transformers/declarations.ts function getDeclarationDiagnostics(host, resolver, file) { const compilerOptions = host.getCompilerOptions(); + const files = filter(getSourceFilesToEmit(host, file), isSourceFileNotJson); const result = transformNodes( resolver, host, factory, compilerOptions, - file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJson), + file ? contains(files, file) ? [file] : emptyArray : files, [transformDeclarations], /*allowDtsFiles*/ false ); return result.diagnostics; } -var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 1 /* AllowUnresolvedNames */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; function transformDeclarations(context) { const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); let getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -110528,8 +110751,7 @@ function transformDeclarations(context) { }); } function reportInferenceFallback(node) { - if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) - return; + if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) return; if (isVariableDeclaration(node) && resolver.isExpandoFunctionDeclaration(node)) { reportExpandoFunctionErrors(node); } else { @@ -110547,7 +110769,7 @@ function transformDeclarations(context) { } } } - } else { + } else if (symbolAccessibilityResult.accessibility !== 3 /* NotResolved */) { const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { @@ -110561,8 +110783,7 @@ function transformDeclarations(context) { return false; } function trackSymbol(symbol, enclosingDeclaration2, meaning) { - if (symbol.flags & 262144 /* TypeParameter */) - return false; + if (symbol.flags & 262144 /* TypeParameter */) return false; const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible( symbol, enclosingDeclaration2, @@ -110647,8 +110868,7 @@ function transformDeclarations(context) { let hasNoDefaultLib = false; const bundle = factory2.createBundle( map(node.sourceFiles, (sourceFile) => { - if (sourceFile.isDeclarationFile) - return void 0; + if (sourceFile.isDeclarationFile) return void 0; hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -110767,22 +110987,19 @@ function transformDeclarations(context) { } function getTypeReferences() { return mapDefined(rawTypeReferenceDirectives, (ref) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; return copyFileReferenceAsSynthetic(ref); }); } function getLibReferences() { return mapDefined(rawLibReferenceDirectives, (ref) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; return copyFileReferenceAsSynthetic(ref); }); } function getReferencedFiles(outputFilePath2) { return mapDefined(rawReferencedFiles, ([sourceFile, ref]) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; const file = host.getSourceFileFromReference(sourceFile, ref); if (!file) { return void 0; @@ -110791,8 +111008,7 @@ function transformDeclarations(context) { if (file.isDeclarationFile) { declFileName = file.fileName; } else { - if (isBundledEmit && contains(node.sourceFiles, file)) - return; + if (isBundledEmit && contains(node.sourceFiles, file)) return; const paths = getOutputPathsFor( file, host, @@ -110801,8 +111017,7 @@ function transformDeclarations(context) { ); declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } - if (!declFileName) - return void 0; + if (!declFileName) return void 0; const fileName = getRelativePathToDirectoryOrUrl( outputFilePath2, declFileName, @@ -111028,8 +111243,7 @@ function transformDeclarations(context) { return setCommentRange(updated, getCommentRange(original)); } function rewriteModuleSpecifier(parent, input) { - if (!input) - return void 0; + if (!input) return void 0; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== 267 /* ModuleDeclaration */ && parent.kind !== 205 /* ImportType */; if (isStringLiteralLike(input)) { if (isBundledEmit) { @@ -111042,8 +111256,7 @@ function transformDeclarations(context) { return input; } function transformImportEqualsDeclaration(decl) { - if (!resolver.isDeclarationVisible(decl)) - return; + if (!resolver.isDeclarationVisible(decl)) return; if (decl.moduleReference.kind === 283 /* ExternalModuleReference */) { const specifier = getExternalModuleImportEqualsDeclarationExpression(decl); return factory2.updateImportEqualsDeclaration( @@ -111172,22 +111385,28 @@ function transformDeclarations(context) { } } function visitDeclarationSubtree(input) { - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; if (isDeclaration(input)) { - if (isDeclarationAndNotVisible(input)) - return; - if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input))) { - if (isolatedDeclarations && isClassDeclaration(input.parent) && isEntityNameExpression(input.name.expression) && resolver.isEntityNameVisible(input.name.expression, input.parent).accessibility === 0 /* Accessible */ && !resolver.isNonNarrowedBindableName(input.name)) { - context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)); + if (isDeclarationAndNotVisible(input)) return; + if (hasDynamicName(input)) { + if (isolatedDeclarations) { + if (isClassDeclaration(input.parent) || isObjectLiteralExpression(input.parent)) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations)); + return; + } else if ( + // Type declarations just need to double-check that the input computed name is an entity name expression + (isInterfaceDeclaration(input.parent) || isTypeLiteralNode(input.parent)) && !isEntityNameExpression(input.name.expression) + ) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)); + return; + } + } else if (!resolver.isLateBound(getParseTreeNode(input)) || !isEntityNameExpression(input.name.expression)) { + return; } - return; } } - if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) - return; - if (isSemicolonClassElement(input)) - return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + if (isSemicolonClassElement(input)) return; let previousEnclosingDeclaration; if (isEnclosingDeclaration(input)) { previousEnclosingDeclaration = enclosingDeclaration; @@ -111199,8 +111418,7 @@ function transformDeclarations(context) { let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */) && input.parent.kind !== 265 /* TypeAliasDeclaration */; if (isMethodDeclaration(input) || isMethodSignature(input)) { if (hasEffectiveModifier(input, 2 /* Private */)) { - if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) - return; + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; return cleanup(factory2.createPropertyDeclaration( ensureModifiers(input), input.name, @@ -111433,8 +111651,7 @@ function transformDeclarations(context) { )); } case 205 /* ImportType */: { - if (!isLiteralImportTypeNode(input)) - return cleanup(input); + if (!isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory2.updateImportTypeNode( input, factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), @@ -111478,8 +111695,7 @@ function transformDeclarations(context) { if (!isPreservedDeclarationStatement(input)) { return; } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { case 278 /* ExportDeclaration */: { if (isSourceFile(input.parent)) { @@ -111553,11 +111769,9 @@ function transformDeclarations(context) { } function transformTopLevelDeclaration(input) { if (lateMarkedStatements) { - while (orderedRemoveItem(lateMarkedStatements, input)) - ; + while (orderedRemoveItem(lateMarkedStatements, input)) ; } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { case 271 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); @@ -111566,12 +111780,9 @@ function transformDeclarations(context) { return transformImportDeclaration(input); } } - if (isDeclaration(input) && isDeclarationAndNotVisible(input)) - return; - if (isJSDocImportTag(input)) - return; - if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) - return; + if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; + if (isJSDocImportTag(input)) return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; let previousEnclosingDeclaration; if (isEnclosingDeclaration(input)) { previousEnclosingDeclaration = enclosingDeclaration; @@ -111775,8 +111986,7 @@ function transformDeclarations(context) { if (ctor) { const oldDiag2 = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, (param) => { - if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) - return; + if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 80 /* Identifier */) { return preserveJsDoc( @@ -111795,8 +112005,7 @@ function transformDeclarations(context) { function walkBindingPattern(pattern) { let elems; for (const elem of pattern.elements) { - if (isOmittedExpression(elem)) - continue; + if (isOmittedExpression(elem)) continue; if (isBindingPattern(elem.name)) { elems = concatenate(elems, walkBindingPattern(elem.name)); } @@ -111896,8 +112105,7 @@ function transformDeclarations(context) { factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, (m) => { - if (shouldStripInternal(m)) - return; + if (shouldStripInternal(m)) return; const enumValue = resolver.getEnumMemberValue(m); const constValue = enumValue == null ? void 0 : enumValue.value; if (isolatedDeclarations && m.initializer && (enumValue == null ? void 0 : enumValue.hasExternalReferences) && // This will be its own compiler error instead, so don't report. @@ -111930,11 +112138,9 @@ function transformDeclarations(context) { } } function transformVariableStatement(input) { - if (!forEach(input.declarationList.declarations, getBindingNameVisible)) - return; + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); - if (!length(nodes)) - return; + if (!length(nodes)) return; const modifiers = factory2.createNodeArray(ensureModifiers(input)); let declList; if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { @@ -111955,8 +112161,7 @@ function transformDeclarations(context) { return; } if (e.name) { - if (!getBindingNameVisible(e)) - return; + if (!getBindingNameVisible(e)) return; if (isBindingPattern(e.name)) { return recreateBindingPattern(e.name); } else { @@ -111982,7 +112187,7 @@ function transformDeclarations(context) { getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node); } errorNameNode = node.name; - Debug.assert(resolver.isLateBound(getParseTreeNode(node))); + Debug.assert(hasDynamicName(node)); const decl = node; const entityName = decl.name.expression; checkEntityNameVisibility(entityName, enclosingDeclaration); @@ -112150,8 +112355,7 @@ function getTransformers(compilerOptions, customTransformers, emitOnly) { }; } function getScriptTransformers(compilerOptions, customTransformers, emitOnly) { - if (emitOnly) - return emptyArray; + if (emitOnly) return emptyArray; const languageVersion = getEmitScriptTarget(compilerOptions); const moduleKind = getEmitModuleKind(compilerOptions); const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); @@ -112581,28 +112785,24 @@ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDt } if (includeBuildInfo) { const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - if (buildInfoPath) - return action( - { buildInfoPath }, - /*sourceFileOrBundle*/ - void 0 - ); + if (buildInfoPath) return action( + { buildInfoPath }, + /*sourceFileOrBundle*/ + void 0 + ); } } } function getTsBuildInfoEmitOutputFilePath(options) { const configFile = options.configFilePath; - if (!isIncrementalCompilation(options)) - return void 0; - if (options.tsBuildInfoFile) - return options.tsBuildInfoFile; + if (!isIncrementalCompilation(options)) return void 0; + if (options.tsBuildInfoFile) return options.tsBuildInfoFile; const outPath = options.outFile; let buildInfoExtensionLess; if (outPath) { buildInfoExtensionLess = removeFileExtension(outPath); } else { - if (!configFile) - return void 0; + if (!configFile) return void 0; const configFileExtensionLess = removeFileExtension(configFile); buildInfoExtensionLess = options.outDir ? options.rootDir ? resolvePath(options.outDir, getRelativePathFromDirectory( options.rootDir, @@ -112659,8 +112859,7 @@ function getOutputDeclarationFileNameWorker(inputFileName, options, ignoreCase, ); } function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2 = () => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)) { - if (configFile.options.emitDeclarationOnly) - return void 0; + if (configFile.options.emitDeclarationOnly) return void 0; const isJsonFile = fileExtensionIs(inputFileName, ".json" /* Json */); const outputFileName = getOutputJSFileNameWorker(inputFileName, configFile.options, ignoreCase, getCommonSourceDirectory2); return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : void 0; @@ -112696,12 +112895,10 @@ function getSingleOutputFileNames(configFile, addOutput) { addOutput(buildInfoPath); } function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2) { - if (isDeclarationFileName(inputFileName)) - return; + if (isDeclarationFileName(inputFileName)) return; const js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); addOutput(js); - if (fileExtensionIs(inputFileName, ".json" /* Json */)) - return; + if (fileExtensionIs(inputFileName, ".json" /* Json */)) return; if (js && configFile.options.sourceMap) { addOutput(`${js}.map`); } @@ -112761,22 +112958,21 @@ function getFirstProjectOutput(configFile, ignoreCase) { } const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); for (const inputFileName of configFile.fileNames) { - if (isDeclarationFileName(inputFileName)) - continue; + if (isDeclarationFileName(inputFileName)) continue; const jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); - if (jsFilePath) - return jsFilePath; - if (fileExtensionIs(inputFileName, ".json" /* Json */)) - continue; + if (jsFilePath) return jsFilePath; + if (fileExtensionIs(inputFileName, ".json" /* Json */)) continue; if (getEmitDeclarations(configFile.options)) { return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); } } const buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options); - if (buildInfoPath) - return buildInfoPath; + if (buildInfoPath) return buildInfoPath; return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`); } +function emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) { + return !!forceDtsEmit && !!emitOnly; +} function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; @@ -112815,8 +113011,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla (_f = tracing) == null ? void 0 : _f.pop(); } function emitBuildInfo(buildInfoPath) { - if (!buildInfoPath || targetSourceFile || emitSkipped) - return; + if (!buildInfoPath || targetSourceFile || emitSkipped) return; if (host.isEmitBlocked(buildInfoPath)) { emitSkipped = true; return; @@ -112846,6 +113041,11 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla emitSkipped = true; return; } + (isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : filter(sourceFileOrBundle.sourceFiles, isSourceFileNotJson)).forEach( + (sourceFile) => { + if (compilerOptions.noCheck || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) markLinkedReferences(sourceFile); + } + ); const transform = transformNodes( resolver, host, @@ -112887,19 +113087,19 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!sourceFileOrBundle || emitOnly === 0 /* Js */) - return; + if (!sourceFileOrBundle || emitOnly === 0 /* Js */) return; if (!declarationFilePath) { - if (emitOnly || compilerOptions.emitDeclarationOnly) - emitSkipped = true; + if (emitOnly || compilerOptions.emitDeclarationOnly) emitSkipped = true; return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson); const inputListOrBundle = compilerOptions.outFile ? [factory.createBundle(filesForEmit)] : filesForEmit; - if (emitOnly && !getEmitDeclarations(compilerOptions)) { - filesForEmit.forEach(collectLinkedAliases); - } + filesForEmit.forEach((sourceFile) => { + if (emitOnly && !getEmitDeclarations(compilerOptions) || compilerOptions.noCheck || emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) { + collectLinkedAliases(sourceFile); + } + }); const declarationTransform = transformNodes( resolver, host, @@ -112982,6 +113182,13 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } forEachChild(node, collectLinkedAliases); } + function markLinkedReferences(file) { + forEachChildRecursively(file, (n) => { + if (isImportEqualsDeclaration(n) && !(getSyntacticModifierFlags(n) & 32 /* Export */)) return "skip"; + if (isImportDeclaration(n)) return "skip"; + resolver.markLinkedReferences(n); + }); + } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform, printer, mapOptions) { const sourceFileOrBundle = transform.transformed[0]; const bundle = sourceFileOrBundle.kind === 308 /* Bundle */ ? sourceFileOrBundle : void 0; @@ -113018,8 +113225,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla sourceFile ); if (sourceMappingURL) { - if (!writer.isAtStartOfLine()) - writer.rawWrite(newLine); + if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); sourceMapUrlPos = writer.getTextPos(); writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); } @@ -113050,8 +113256,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla return sourceRoot ? ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; } function getSourceMapDirectory(mapOptions, filePath, sourceFile) { - if (mapOptions.sourceRoot) - return host.getCommonSourceDirectory(); + if (mapOptions.sourceRoot) return host.getCommonSourceDirectory(); if (mapOptions.mapRoot) { let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); if (sourceFile) { @@ -113115,10 +113320,11 @@ var notImplementedResolver = { isValueAliasDeclaration: notImplemented, isReferencedAliasDeclaration: notImplemented, isTopLevelValueImportEqualsWithEntityName: notImplemented, - getNodeCheckFlags: notImplemented, + hasNodeCheckFlag: notImplemented, isDeclarationVisible: notImplemented, isLateBound: (_node) => false, collectLinkedAliases: notImplemented, + markLinkedReferences: notImplemented, isImplementationOfOverload: notImplemented, requiresAddingImplicitUndefined: notImplemented, isExpandoFunctionDeclaration: notImplemented, @@ -113139,7 +113345,6 @@ var notImplementedResolver = { isArgumentsLocalBinding: notImplemented, getExternalModuleFileFromDeclaration: notImplemented, isLiteralConstDeclaration: notImplemented, - isNonNarrowedBindableName: notImplemented, getJsxFactoryEntity: notImplemented, getJsxFragmentFactoryEntity: notImplemented, isBindingCapturedByNode: notImplemented, @@ -113384,13 +113589,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile))); } function emit(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); } function emitIdentifierName(node) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit( 2 /* IdentifierName */, node, @@ -113399,8 +113602,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { ); } function emitExpression(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { @@ -113480,20 +113682,15 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitSnippetNode(hint, node, snippet); } } - if (hint === 0 /* SourceFile */) - return emitSourceFile(cast(node, isSourceFile)); - if (hint === 2 /* IdentifierName */) - return emitIdentifier(cast(node, isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return emitLiteral( - cast(node, isStringLiteral), - /*jsxAttributeEscape*/ - true - ); - if (hint === 3 /* MappedTypeParameter */) - return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); - if (hint === 7 /* ImportTypeNodeAttributes */) - return emitImportTypeNodeAttributes(cast(node, isImportAttributes)); + if (hint === 0 /* SourceFile */) return emitSourceFile(cast(node, isSourceFile)); + if (hint === 2 /* IdentifierName */) return emitIdentifier(cast(node, isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) return emitLiteral( + cast(node, isStringLiteral), + /*jsxAttributeEscape*/ + true + ); + if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); + if (hint === 7 /* ImportTypeNodeAttributes */) return emitImportTypeNodeAttributes(cast(node, isImportAttributes)); if (hint === 5 /* EmbeddedStatement */) { Debug.assertNode(node, isEmptyStatement); return emitEmptyStatement( @@ -113912,10 +114109,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { return Debug.fail("SyntheticReferenceExpression should not be printed"); } } - if (isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); - if (isTokenKind(node.kind)) - return writeTokenNode(node, writePunctuation); + if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); + if (isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`); } function emitMappedTypeParameter(node) { @@ -113948,8 +114143,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (helpers) { for (const helper of helpers) { if (!helper.scoped) { - if (shouldSkip) - continue; + if (shouldSkip) continue; if (shouldBundle) { if (bundledHelpers.get(helper.name)) { continue; @@ -114043,13 +114237,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitComputedPropertyName(node) { - const savedPrivateNameTempFlags = privateNameTempFlags; - const savedReservedMemberNames = reservedPrivateNames; - popPrivateNameGenerationScope(); writePunctuation("["); emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); - pushPrivateNameGenerationScope(savedPrivateNameTempFlags, savedReservedMemberNames); } function emitTypeParameter(node) { emitModifierList(node, node.modifiers); @@ -114110,15 +114300,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { writeTrailingSemicolon(); } function emitMethodSignature(node) { - pushNameGenerationScope(node); emitModifierList(node, node.modifiers); emit(node.name); emit(node.questionToken); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitMethodDeclaration(node) { emitDecoratorsAndModifiers( @@ -114130,11 +114315,13 @@ function createPrinter(printerOptions = {}, handlers = {}) { emit(node.asteriskToken); emit(node.name); emit(node.questionToken); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitClassStaticBlockDeclaration(node) { writeKeyword("static"); + pushNameGenerationScope(node); emitBlockFunctionBody(node.body); + popNameGenerationScope(node); } function emitConstructor(node) { emitDecoratorsAndModifiers( @@ -114144,7 +114331,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { false ); writeKeyword("constructor"); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitAccessorDeclaration(node) { const pos = emitDecoratorsAndModifiers( @@ -114157,25 +114344,15 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTokenWithComment(token, pos, writeKeyword, node); writeSpace(); emit(node.name); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitCallSignature(node) { - pushNameGenerationScope(node); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitConstructSignature(node) { - pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitIndexSignature(node) { emitDecoratorsAndModifiers( @@ -114213,14 +114390,17 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { - pushNameGenerationScope(node); + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); + } + function emitFunctionTypeHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); + } + function emitFunctionTypeBody(node) { writeSpace(); emit(node.type); - popNameGenerationScope(node); } function emitJSDocFunctionType(node) { writeKeyword("function"); @@ -114241,17 +114421,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { writePunctuation("="); } function emitConstructorType(node) { - pushNameGenerationScope(node); emitModifierList(node, node.modifiers); writeKeyword("new"); writeSpace(); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - writeSpace(); - writePunctuation("=>"); - writeSpace(); - emit(node.type); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -114260,16 +114433,13 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTypeArguments(node, node.typeArguments); } function emitTypeLiteral(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); writePunctuation("{"); const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); - popPrivateNameGenerationScope(); + popNameGenerationScope(node); } function emitArrayType(node) { emit(node.elementType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); @@ -114441,11 +114611,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushNameGenerationScope(node); forEach(node.properties, generateMemberNames); const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; if (indentedFlag) { @@ -114457,7 +114623,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (indentedFlag) { decreaseIndent(); } - popPrivateNameGenerationScope(); + popNameGenerationScope(node); } function emitPropertyAccessExpression(node) { emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); @@ -114572,7 +114738,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } function emitArrowFunction(node) { emitModifierList(node, node.modifiers); - emitSignatureAndBody(node, emitArrowFunctionHead); + emitSignatureAndBody(node, emitArrowFunctionHead, emitArrowFunctionBody); } function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); @@ -114581,6 +114747,14 @@ function createPrinter(printerOptions = {}, handlers = {}) { writeSpace(); emit(node.equalsGreaterThanToken); } + function emitArrowFunctionBody(node) { + if (isBlock(node.body)) { + emitBlockFunctionBody(node.body); + } else { + writeSpace(); + emitExpression(node.body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); + } + } function emitDeleteExpression(node) { emitTokenWithComment(91 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); @@ -114636,10 +114810,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { const emitComments2 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); - if (emitComments2) - emitCommentsBeforeNode(node); - if (emitSourceMaps) - emitSourceMapsBeforeNode(node); + if (emitComments2) emitCommentsBeforeNode(node); + if (emitSourceMaps) emitSourceMapsBeforeNode(node); beforeEmitNode(node); } else { state = { @@ -114690,10 +114862,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { const shouldEmitComments2 = state.shouldEmitCommentsStack[state.stackIndex]; const shouldEmitSourceMaps2 = state.shouldEmitSourceMapsStack[state.stackIndex]; afterEmitNode(savedPreserveSourceNewlines); - if (shouldEmitSourceMaps2) - emitSourceMapsAfterNode(node); - if (shouldEmitComments2) - emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + if (shouldEmitSourceMaps2) emitSourceMapsAfterNode(node); + if (shouldEmitComments2) emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); state.stackIndex--; } @@ -114999,8 +115169,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; } function willEmitLeadingNewLine(node) { - if (!currentSourceFile) - return false; + if (!currentSourceFile) return false; const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (leadingCommentRanges) { const parseNode = getParseTreeNode(node); @@ -115008,14 +115177,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } } - if (some(leadingCommentRanges, commentWillEmitNewLine)) - return true; - if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) - return true; + if (some(leadingCommentRanges, commentWillEmitNewLine)) return true; + if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) return true; if (isPartiallyEmittedExpression(node)) { if (node.pos !== node.expression.pos) { - if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) - return true; + if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) return true; } return willEmitLeadingNewLine(node.expression); } @@ -115128,35 +115294,33 @@ function createPrinter(printerOptions = {}, handlers = {}) { emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } - function emitSignatureAndBody(node, emitSignatureHead2) { + function emitSignatureAndBody(node, emitSignatureHead2, emitBody) { + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + forEach(node.parameters, generateNames); + emitSignatureHead2(node); + emitBody(node); + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } + } + function emitFunctionBody(node) { const body = node.body; if (body) { - if (isBlock(body)) { - const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; - if (indentedFlag) { - increaseIndent(); - } - pushNameGenerationScope(node); - forEach(node.parameters, generateNames); - generateNames(node.body); - emitSignatureHead2(node); - emitBlockFunctionBody(body); - popNameGenerationScope(node); - if (indentedFlag) { - decreaseIndent(); - } - } else { - emitSignatureHead2(node); - writeSpace(); - emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); - } + emitBlockFunctionBody(body); } else { - emitSignatureHead2(node); writeTrailingSemicolon(); } } + function emitEmptyFunctionBody(_node) { + writeTrailingSemicolon(); + } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); @@ -115185,6 +115349,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } function emitBlockFunctionBody(body) { + generateNames(body); onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); @@ -115225,12 +115390,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); - forEach(node.members, generateMemberNames); emitDecoratorsAndModifiers( node, node.modifiers, @@ -115250,19 +115409,16 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); emitList(node, node.members, 129 /* ClassMembers */); + popNameGenerationScope(node); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } - popPrivateNameGenerationScope(); } function emitInterfaceDeclaration(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); emitDecoratorsAndModifiers( node, node.modifiers, @@ -115276,9 +115432,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); emitList(node, node.members, 129 /* InterfaceMembers */); + popNameGenerationScope(node); writePunctuation("}"); - popPrivateNameGenerationScope(); } function emitTypeAliasDeclaration(node) { emitDecoratorsAndModifiers( @@ -115325,8 +115483,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } emit(node.name); let body = node.body; - if (!body) - return writeTrailingSemicolon(); + if (!body) return writeTrailingSemicolon(); while (body && isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); @@ -115894,8 +116051,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { - if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + if (node.isDeclarationFile) emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs2) { if (hasNoDefaultLib) { @@ -116015,8 +116171,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitNodeWithWriter(node, writer2) { - if (!node) - return; + if (!node) return; const savedWrite = write; write = writer2; emit(node); @@ -116051,10 +116206,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { pos++; } const textRange = { pos: -1, end: -1 }; - if (start === 0) - textRange.pos = modifiers.pos; - if (pos === modifiers.length - 1) - textRange.end = modifiers.end; + if (start === 0) textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) textRange.end = modifiers.end; if (lastMode === "modifiers" || allowDecorators) { emitNodeListItems( emit, @@ -116659,6 +116812,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { return getLiteralText(node, currentSourceFile, flags); } function pushNameGenerationScope(node) { + privateNameTempFlagsStack.push(privateNameTempFlags); + privateNameTempFlags = 0 /* Auto */; + reservedPrivateNamesStack.push(reservedPrivateNames); if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { return; } @@ -116669,6 +116825,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { + privateNameTempFlags = privateNameTempFlagsStack.pop(); + reservedPrivateNames = reservedPrivateNamesStack.pop(); if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { return; } @@ -116682,16 +116840,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { } reservedNames.add(name); } - function pushPrivateNameGenerationScope(newPrivateNameTempFlags, newReservedMemberNames) { - privateNameTempFlagsStack.push(privateNameTempFlags); - privateNameTempFlags = newPrivateNameTempFlags; - reservedPrivateNamesStack.push(reservedNames); - reservedPrivateNames = newReservedMemberNames; - } - function popPrivateNameGenerationScope() { - privateNameTempFlags = privateNameTempFlagsStack.pop(); - reservedPrivateNames = reservedPrivateNamesStack.pop(); - } function reservePrivateNameInNestedScopes(name) { if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) { reservedPrivateNames = /* @__PURE__ */ new Set(); @@ -116699,8 +116847,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { reservedPrivateNames.add(name); } function generateNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 241 /* Block */: forEach(node.statements, generateNames); @@ -116785,13 +116932,14 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function generateMemberNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: case 177 /* GetAccessor */: case 178 /* SetAccessor */: generateNameIfNeeded(node.name); @@ -116825,7 +116973,28 @@ function createPrinter(printerOptions = {}, handlers = {}) { return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); } function isReservedName(name, privateName) { - return privateName ? !!(reservedPrivateNames == null ? void 0 : reservedPrivateNames.has(name)) : !!(reservedNames == null ? void 0 : reservedNames.has(name)); + let set; + let stack; + if (privateName) { + set = reservedPrivateNames; + stack = reservedPrivateNamesStack; + } else { + set = reservedNames; + stack = reservedNamesStack; + } + if (set == null ? void 0 : set.has(name)) { + return true; + } + for (let i = stack.length - 1; i >= 0; i--) { + if (set === stack[i]) { + continue; + } + set = stack[i]; + if (set == null ? void 0 : set.has(name)) { + return true; + } + } + return false; } function isFileLevelUniqueNameInCurrentFile(name, _isPrivate) { return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; @@ -117314,8 +117483,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; if (!hasWrittenComment) { emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); hasWrittenComment = true; @@ -117343,8 +117511,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; if (!writer.isAtStartOfLine()) { writer.writeSpace(" "); } @@ -117364,8 +117531,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { exitComment(); } function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -117374,8 +117540,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -117409,8 +117574,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return detachedCommentsInfo !== void 0 && last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; const pos = last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); @@ -117436,8 +117600,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitComment(text, lineMap, writer2, commentPos, commentEnd, newLine2) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; emitPos(commentPos); writeCommentRange(text, lineMap, writer2, commentPos, commentEnd, newLine2); emitPos(commentEnd); @@ -117514,8 +117677,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitSourcePos(source, tokenPos); } tokenPos = emitCallback(token, writer2, tokenPos); - if (range) - tokenPos = range.end; + if (range) tokenPos = range.end; if ((emitFlags & 512 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { emitSourcePos(source, tokenPos); } @@ -117717,8 +117879,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi return result !== void 0 ? result || getFileSystemEntriesFromHost(dir, path) : emptyFileSystemEntries; } function getFileSystemEntriesFromHost(dir, path) { - if (rootSymLinkResult && path === rootDirPath) - return rootSymLinkResult; + if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; const result = { files: map(host.readDirectory( dir, @@ -117731,8 +117892,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi ), getBaseNameOfFileName) || emptyArray, directories: host.getDirectories(dir) || emptyArray }; - if (path === rootDirPath) - rootSymLinkResult = result; + if (path === rootDirPath) rootSymLinkResult = result; return result; } } @@ -117813,8 +117973,7 @@ function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedCon watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: () => { const existing2 = extendedConfigFilesMap.get(extendedConfigFilePath); - if (!existing2 || existing2.projects.size !== 0) - return; + if (!existing2 || existing2.projects.size !== 0) return; existing2.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); } @@ -117824,13 +117983,11 @@ function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedCon } function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { extendedConfigFilesMap.forEach((watcher) => { - if (watcher.projects.delete(projectPath)) - watcher.close(); + if (watcher.projects.delete(projectPath)) watcher.close(); }); } function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) { - if (!extendedConfigCache.delete(extendedConfigFilePath)) - return; + if (!extendedConfigCache.delete(extendedConfigFilePath)) return; extendedConfigCache.forEach(({ extendedResult }, key) => { var _a; if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile) => toPath3(extendedFile) === extendedConfigFilePath)) { @@ -117902,8 +118059,7 @@ function isIgnoredFileFromWildCardWatching({ return true; } fileOrDirectoryPath = newPath; - if (fileOrDirectoryPath === watchedDirPath) - return false; + if (fileOrDirectoryPath === watchedDirPath) return false; if (hasExtension(fileOrDirectoryPath) && !(isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions) || isSupportedScriptKind())) { writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; @@ -117912,13 +118068,10 @@ function isIgnoredFileFromWildCardWatching({ writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } - if (!program) - return false; - if (options.outFile || options.outDir) - return false; + if (!program) return false; + if (options.outFile || options.outDir) return false; if (isDeclarationFileName(fileOrDirectoryPath)) { - if (options.declarationDir) - return false; + if (options.declarationDir) return false; } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) { return false; } @@ -117934,8 +118087,7 @@ function isIgnoredFileFromWildCardWatching({ return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); } function isSupportedScriptKind() { - if (!getScriptKind) - return false; + if (!getScriptKind) return false; const scriptKind = getScriptKind(fileOrDirectory); switch (scriptKind) { case 3 /* TS */: @@ -118211,8 +118363,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { const readFileWithCache = (fileName) => { const key = toPath3(fileName); const value = readFileCache.get(key); - if (value !== void 0) - return value !== false ? value : void 0; + if (value !== void 0) return value !== false ? value : void 0; return setReadFileCache(key, fileName); }; const setReadFileCache = (key, fileName) => { @@ -118223,8 +118374,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.readFile = (fileName) => { const key = toPath3(fileName); const value = readFileCache.get(key); - if (value !== void 0) - return value !== false ? value : void 0; + if (value !== void 0) return value !== false ? value : void 0; if (!fileExtensionIs(fileName, ".json" /* Json */) && !isBuildInfoFile(fileName)) { return originalReadFile.call(host, fileName); } @@ -118235,8 +118385,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0; const forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat); const value = forImpliedNodeFormat == null ? void 0 : forImpliedNodeFormat.get(key); - if (value) - return value; + if (value) return value; const sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile); if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */))) { sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || /* @__PURE__ */ new Map()).set(key, sourceFile)); @@ -118246,8 +118395,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.fileExists = (fileName) => { const key = toPath3(fileName); const value = fileExistsCache.get(key); - if (value !== void 0) - return value; + if (value !== void 0) return value; const newValue = originalFileExists.call(host, fileName); fileExistsCache.set(key, !!newValue); return newValue; @@ -118275,8 +118423,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.directoryExists = (directory) => { const key = toPath3(directory); const value = directoryExistsCache.get(key); - if (value !== void 0) - return value; + if (value !== void 0) return value; const newValue = originalDirectoryExists.call(host, directory); directoryExistsCache.set(key, !!newValue); return newValue; @@ -118488,8 +118635,7 @@ function getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions) { return fileEmitMode === 1 /* CommonJS */ ? 1 /* CommonJS */ : emitModuleKindIsNonNodeESM(fileEmitMode) || fileEmitMode === 200 /* Preserve */ ? 99 /* ESNext */ : void 0; } function getResolutionModeOverride(node, grammarErrorOnNode) { - if (!node) - return void 0; + if (!node) return void 0; if (length(node.elements) !== 1) { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( node, @@ -118498,8 +118644,7 @@ function getResolutionModeOverride(node, grammarErrorOnNode) { return void 0; } const elem = node.elements[0]; - if (!isStringLiteralLike(elem.name)) - return void 0; + if (!isStringLiteralLike(elem.name)) return void 0; if (elem.name.text !== "resolution-mode") { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( elem.name, @@ -118507,8 +118652,7 @@ function getResolutionModeOverride(node, grammarErrorOnNode) { ); return void 0; } - if (!isStringLiteralLike(elem.value)) - return void 0; + if (!isStringLiteralLike(elem.value)) return void 0; if (elem.value.text !== "import" && elem.value.text !== "require") { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.value, Diagnostics.resolution_mode_should_be_either_require_or_import); return void 0; @@ -118541,7 +118685,7 @@ function createModuleResolutionLoader(containingFile, redirectedReference, optio }; } function getTypeReferenceResolutionName(entry) { - return !isString(entry) ? toFileNameLowerCase(entry.fileName) : entry; + return !isString(entry) ? entry.fileName : entry; } var typeReferenceResolutionNameAndModeGetter = { getName: getTypeReferenceResolutionName, @@ -118562,8 +118706,7 @@ function createTypeReferenceResolutionLoader(containingFile, redirectedReference }; } function loadWithModeAwareCache(entries, containingFile, redirectedReference, options, containingSourceFile, host, resolutionCache, createLoader) { - if (entries.length === 0) - return emptyArray; + if (entries.length === 0) return emptyArray; const resolutions = []; const cache = /* @__PURE__ */ new Map(); const loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache); @@ -118598,16 +118741,14 @@ function forEachProjectReference(projectReferences, resolvedProjectReferences, c function worker(projectReferences2, resolvedProjectReferences2, parent) { if (cbRef) { const result = cbRef(projectReferences2, parent); - if (result) - return result; + if (result) return result; } return forEach(resolvedProjectReferences2, (resolvedRef, index) => { if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) { return void 0; } const result = cbResolvedRef(resolvedRef, parent, index); - if (result || !resolvedRef) - return result; + if (result || !resolvedRef) return result; (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef); }); @@ -118628,10 +118769,12 @@ function getLibraryNameFromLibFileName(libFileName) { } return "@typescript/lib-" + path; } +function getLibNameFromLibReference(libReference) { + return toFileNameLowerCase(libReference.fileName); +} function getLibFileNameFromLibReference(libReference) { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); - return { libName, libFileName }; + const libName = getLibNameFromLibReference(libReference); + return libMap.get(libName); } function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { @@ -118651,13 +118794,12 @@ function getReferencedFileLocation(program, ref) { var _a, _b, _c, _d; const file = Debug.checkDefined(program.getSourceFileByPath(ref.file)); const { kind, index } = ref; - let pos, end, packageId, resolutionMode; + let pos, end, packageId; switch (kind) { case 3 /* Import */: const importLiteral = getModuleNameStringLiteralAt(file, index); - packageId = (_b = (_a = program.getResolvedModule(file, importLiteral.text, program.getModeForUsageLocation(file, importLiteral))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; - if (importLiteral.pos === -1) - return { file, packageId, text: importLiteral.text }; + packageId = (_b = (_a = program.getResolvedModuleFromModuleSpecifier(importLiteral, file)) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; + if (importLiteral.pos === -1) return { file, packageId, text: importLiteral.text }; pos = skipTrivia(file.text, importLiteral.pos); end = importLiteral.end; break; @@ -118665,8 +118807,8 @@ function getReferencedFileLocation(program, ref) { ({ pos, end } = file.referencedFiles[index]); break; case 5 /* TypeReferenceDirective */: - ({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]); - packageId = (_d = (_c = program.getResolvedTypeReferenceDirective(file, toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; + ({ pos, end } = file.typeReferenceDirectives[index]); + packageId = (_d = (_c = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(file.typeReferenceDirectives[index], file)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; break; case 7 /* LibReferenceDirective */: ({ pos, end } = file.libReferenceDirectives[index]); @@ -118677,25 +118819,17 @@ function getReferencedFileLocation(program, ref) { return { file, pos, end, packageId }; } function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { - if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) - return false; - if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) - return false; + if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; + if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; let seenResolvedRefs; - if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) - return false; - if (program.getSourceFiles().some(sourceFileNotUptoDate)) - return false; + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) return false; + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; const missingPaths = program.getMissingFilePaths(); - if (missingPaths && forEachEntry(missingPaths, fileExists)) - return false; + if (missingPaths && forEachEntry(missingPaths, fileExists)) return false; const currentOptions = program.getCompilerOptions(); - if (!compareDataObjects(currentOptions, newOptions)) - return false; - if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) - return false; - if (currentOptions.configFile && newOptions.configFile) - return currentOptions.configFile.text === newOptions.configFile.text; + if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) return false; + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolutions(sourceFile.path); @@ -118708,16 +118842,12 @@ function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (contains(seenResolvedRefs, oldResolvedRef)) - return true; + if (contains(seenResolvedRefs, oldResolvedRef)) return true; const refPath2 = resolveProjectReferencePath(oldRef); const newParsedCommandLine = getParsedCommandLine(refPath2); - if (!newParsedCommandLine) - return false; - if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) - return false; - if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) - return false; + if (!newParsedCommandLine) return false; + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) return false; + if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); return !forEach(oldResolvedRef.references, (childResolvedRef, index) => !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index])); } @@ -118838,8 +118968,7 @@ var plainJSErrors = /* @__PURE__ */ new Set([ Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code ]); function shouldProgramCreateNewSourceFiles(program, newOptions) { - if (!program) - return false; + if (!program) return false; return optionsHaveChanges(program.getCompilerOptions(), newOptions, sourceFileAffectingCompilerOptions); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion2) { @@ -118857,6 +118986,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion2 } = createProgramOptions; let { oldProgram } = createProgramOptions; + for (const option of commandLineOptionOfCustomType) { + if (hasProperty(options, option.name)) { + if (typeof options[option.name] === "string") { + throw new Error(`${option.name} is a string value; tsconfig JSON must be parsed with parseJsonSourceFileConfigFileContent or getParsedCommandLineOfConfigFile before passing to createProgram`); + } + } + } const reportInvalidIgnoreDeprecations = memoize(() => createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations)); let processingDefaultLibFiles; let processingOtherFiles; @@ -118867,9 +119003,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let classifiableNames; const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */ new Map(); let fileReasons = createMultiMap(); + let filesWithReferencesProcessed; + let fileReasonsToChain; + let reasonToRelatedInfo; const cachedBindAndCheckDiagnosticsForFile = {}; const cachedDeclarationDiagnosticsForFile = {}; - let resolvedTypeReferenceDirectives = createModeAwareCache(); let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; @@ -118898,6 +119036,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options)); const defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : getDirectoryPath(getDefaultLibraryFileName()); const programDiagnostics = createDiagnosticCollection(); + let lazyProgramDiagnosticExplainingFile = []; const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); @@ -119015,8 +119154,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } if (rootNames.length) { resolvedProjectReferences == null ? void 0 : resolvedProjectReferences.forEach((parsedRef, index) => { - if (!parsedRef) - return; + if (!parsedRef) return; const out = parsedRef.commandLine.options.outFile; if (useSourceOfProjectReferenceRedirect) { if (out || getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { @@ -119104,6 +119242,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config files = stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = void 0; processingOtherFiles = void 0; + filesWithReferencesProcessed = void 0; } if (oldProgram && host.onReleaseOldSourceFile) { const oldSourceFiles = oldProgram.getSourceFiles(); @@ -119174,7 +119313,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getInstantiationCount: () => getTypeChecker().getInstantiationCount(), getRelationCacheSizes: () => getTypeChecker().getRelationCacheSizes(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics, - getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, getAutomaticTypeDirectiveNames: () => automaticTypeDirectiveNames, getAutomaticTypeDirectiveResolutions: () => automaticTypeDirectiveResolutions, isSourceFileFromExternalLibrary, @@ -119193,6 +119331,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getResolvedModule, getResolvedModuleFromModuleSpecifier, getResolvedTypeReferenceDirective, + getResolvedTypeReferenceDirectiveFromTypeReferenceDirective, forEachResolvedModule, forEachResolvedTypeReferenceDirective, getCurrentPackagesMap: () => packageMap, @@ -119226,30 +119365,70 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config writeFile: writeFile2 }; onProgramCreateComplete(); - fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { - switch (diagnostic.kind) { - case 1 /* FilePreprocessingFileExplainingDiagnostic */: - return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || emptyArray)); - case 0 /* FilePreprocessingReferencedDiagnostic */: - const { file, pos, end } = getReferencedFileLocation(program, diagnostic.reason); - return programDiagnostics.add(createFileDiagnostic(file, Debug.checkDefined(pos), Debug.checkDefined(end) - pos, diagnostic.diagnostic, ...diagnostic.args || emptyArray)); - case 2 /* ResolutionDiagnostics */: - return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d)); - default: - Debug.assertNever(diagnostic); - } - }); verifyCompilerOptions(); mark("afterProgram"); measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function updateAndGetProgramDiagnostics() { + if (lazyProgramDiagnosticExplainingFile) { + fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { + switch (diagnostic.kind) { + case 1 /* FilePreprocessingFileExplainingDiagnostic */: + return programDiagnostics.add( + createDiagnosticExplainingFile( + diagnostic.file && getSourceFileByPath(diagnostic.file), + diagnostic.fileProcessingReason, + diagnostic.diagnostic, + diagnostic.args || emptyArray + ) + ); + case 0 /* FilePreprocessingLibReferenceDiagnostic */: + return programDiagnostics.add(filePreprocessingLibreferenceDiagnostic(diagnostic)); + case 2 /* ResolutionDiagnostics */: + return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d)); + default: + Debug.assertNever(diagnostic); + } + }); + lazyProgramDiagnosticExplainingFile.forEach( + ({ file, diagnostic, args }) => programDiagnostics.add( + createDiagnosticExplainingFile( + file, + /*fileProcessingReason*/ + void 0, + diagnostic, + args + ) + ) + ); + lazyProgramDiagnosticExplainingFile = void 0; + fileReasonsToChain = void 0; + reasonToRelatedInfo = void 0; + } + return programDiagnostics; + } + function filePreprocessingLibreferenceDiagnostic({ reason }) { + const { file, pos, end } = getReferencedFileLocation(program, reason); + const libReference = file.libReferenceDirectives[reason.index]; + const libName = getLibNameFromLibReference(libReference); + const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); + const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); + return createFileDiagnostic( + file, + Debug.checkDefined(pos), + Debug.checkDefined(end) - pos, + suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0, + libName, + suggestion + ); + } function getResolvedModule(file, moduleName, mode) { var _a2; return (_a2 = resolvedModules == null ? void 0 : resolvedModules.get(file.path)) == null ? void 0 : _a2.get(moduleName, mode); } - function getResolvedModuleFromModuleSpecifier(moduleSpecifier) { - const sourceFile = getSourceFileOfNode(moduleSpecifier); + function getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile) { + sourceFile ?? (sourceFile = getSourceFileOfNode(moduleSpecifier)); Debug.assertIsDefined(sourceFile, "`moduleSpecifier` must have a `SourceFile` ancestor. Use `program.getResolvedModule` instead to provide the containing file and resolution mode."); return getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation2(sourceFile, moduleSpecifier)); } @@ -119257,6 +119436,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config var _a2; return (_a2 = resolvedTypeReferenceDirectiveNames == null ? void 0 : resolvedTypeReferenceDirectiveNames.get(file.path)) == null ? void 0 : _a2.get(typeDirectiveName, mode); } + function getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeRef, sourceFile) { + return getResolvedTypeReferenceDirective(sourceFile, typeRef.fileName, typeRef.resolutionMode || sourceFile.impliedNodeFormat); + } function forEachResolvedModule(callback, file) { forEachResolution(resolvedModules, callback, file); } @@ -119265,18 +119447,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function forEachResolution(resolutionCache, callback, file) { var _a2; - if (file) - (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); - else - resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); + if (file) (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); + else resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); } function getPackagesMap() { - if (packageMap) - return packageMap; + if (packageMap) return packageMap; packageMap = /* @__PURE__ */ new Map(); forEachResolvedModule(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + if (resolvedModule == null ? void 0 : resolvedModule.packageId) packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); }); return packageMap; } @@ -119288,29 +119466,24 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function addResolutionDiagnostics(resolution) { var _a2; - if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) - return; + if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) return; (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ kind: 2 /* ResolutionDiagnostics */, diagnostics: resolution.resolutionDiagnostics }); } function addResolutionDiagnosticsFromResolutionOrCache(containingFile, name, resolution, mode) { - if (host.resolveModuleNameLiterals || !host.resolveModuleNames) - return addResolutionDiagnostics(resolution); - if (!moduleResolutionCache || isExternalModuleNameRelative(name)) - return; + if (host.resolveModuleNameLiterals || !host.resolveModuleNames) return addResolutionDiagnostics(resolution); + if (!moduleResolutionCache || isExternalModuleNameRelative(name)) return; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const containingDir = getDirectoryPath(containingFileName); const redirectedReference = getRedirectReferenceForResolution(containingFile); const fromCache = moduleResolutionCache.getFromNonRelativeNameCache(name, mode, containingDir, redirectedReference); - if (fromCache) - addResolutionDiagnostics(fromCache); + if (fromCache) addResolutionDiagnostics(fromCache); } function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { var _a2, _b2; - if (!moduleNames.length) - return emptyArray; + if (!moduleNames.length) return emptyArray; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const redirectedReference = getRedirectReferenceForResolution(containingFile); (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName }); @@ -119323,8 +119496,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) { var _a2, _b2; - if (!typeDirectiveNames.length) - return []; + if (!typeDirectiveNames.length) return []; const containingSourceFile = !isString(containingFile) ? containingFile : void 0; const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile); @@ -119338,26 +119510,20 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getRedirectReferenceForResolution(file) { const redirect = getResolvedProjectReferenceToRedirect(file.originalFileName); - if (redirect || !isDeclarationFileName(file.originalFileName)) - return redirect; + if (redirect || !isDeclarationFileName(file.originalFileName)) return redirect; const resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path); - if (resultFromDts) - return resultFromDts; - if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) - return void 0; + if (resultFromDts) return resultFromDts; + if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return void 0; const realDeclarationPath = toPath3(host.realpath(file.originalFileName)); return realDeclarationPath === file.path ? void 0 : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath); } function getRedirectReferenceForResolutionFromSourceOfProject(filePath) { const source = getSourceOfProjectReferenceRedirect(filePath); - if (isString(source)) - return getResolvedProjectReferenceToRedirect(source); - if (!source) - return void 0; + if (isString(source)) return getResolvedProjectReferenceToRedirect(source); + if (!source) return void 0; return forEachResolvedProjectReference2((resolvedRef) => { const out = resolvedRef.commandLine.options.outFile; - if (!out) - return void 0; + if (!out) return void 0; return toPath3(out) === filePath ? resolvedRef : void 0; }); } @@ -119372,12 +119538,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config false )) { const basename = getBaseFileName(a.fileName); - if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") - return 0; + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") return 0; const name = removeSuffix(removePrefix(basename, "lib."), ".d.ts"); const index = libs.indexOf(name); - if (index !== -1) - return index + 1; + if (index !== -1) return index + 1; } return libs.length + 2; } @@ -119528,8 +119692,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry); } - if (!unknownTypeReferenceDirectiveNames) - return result || emptyArray; + if (!unknownTypeReferenceDirectiveNames) return result || emptyArray; const resolutions = resolveTypeReferenceDirectiveNamesWorker( unknownTypeReferenceDirectiveNames, containingFile, @@ -119695,8 +119858,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (name) => oldProgram.getResolvedModule(newSourceFile, name.text, getModeForUsageLocation2(newSourceFile, name)), moduleResolutionIsEqualTo ); - if (resolutionsChanged) - structureIsReused = 1 /* SafeModules */; + if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; const typesReferenceDirectives = newSourceFile.typeReferenceDirectives; const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile); (resolvedTypeReferenceDirectiveNamesProcessing ?? (resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, typeReferenceResolutions); @@ -119706,8 +119868,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (name) => oldProgram.getResolvedTypeReferenceDirective(newSourceFile, getTypeReferenceResolutionName(name), getModeForFileReference(name, newSourceFile.impliedNodeFormat)), typeDirectiveIsEqualTo ); - if (typeReferenceResolutionsChanged) - structureIsReused = 1 /* SafeModules */; + if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; } if (structureIsReused !== 2 /* Completely */) { return structureIsReused; @@ -119719,12 +119880,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return 1 /* SafeModules */; } if (host.hasChangedAutomaticTypeDirectiveNames) { - if (host.hasChangedAutomaticTypeDirectiveNames()) - return 1 /* SafeModules */; + if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; } else { automaticTypeDirectiveNames = getAutomaticTypeDirectiveNames(options, host); - if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames)) - return 1 /* SafeModules */; + if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames)) return 1 /* SafeModules */; } missingFileNames = oldProgram.getMissingFilePaths(); Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); @@ -119748,7 +119907,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config files = newSourceFiles; fileReasons = oldProgram.getFileIncludeReasons(); fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); automaticTypeDirectiveNames = oldProgram.getAutomaticTypeDirectiveNames(); automaticTypeDirectiveResolutions = oldProgram.getAutomaticTypeDirectiveResolutions(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; @@ -119783,10 +119941,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config readFile: (f) => host.readFile(f), fileExists: (f) => { const path = toPath3(f); - if (getSourceFileByPath(path)) - return true; - if (missingFileNames.has(path)) - return false; + if (getSourceFileByPath(path)) return true; + if (missingFileNames.has(path)) return false; return host.fileExists(f); }, realpath: maybeBind(host, host.realpath), @@ -119882,20 +120038,27 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit) { if (!forceDtsEmit) { const result = handleNoEmitOptions(program2, sourceFile, writeFileCallback, cancellationToken); - if (result) - return result; + if (result) return result; } - const emitResolver = getTypeChecker().getEmitResolver(options.outFile ? void 0 : sourceFile, cancellationToken); + const typeChecker2 = getTypeChecker(); + const emitResolver = typeChecker2.getEmitResolver( + options.outFile ? void 0 : sourceFile, + cancellationToken, + emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) + ); mark("beforeEmit"); - const emitResult = emitFiles( - emitResolver, - getEmitHost(writeFileCallback), - sourceFile, - getTransformers(options, customTransformers, emitOnly), - emitOnly, - /*onlyBuildInfo*/ - false, - forceDtsEmit + const emitResult = typeChecker2.runWithCancellationToken( + cancellationToken, + () => emitFiles( + emitResolver, + getEmitHost(writeFileCallback), + sourceFile, + getTransformers(options, customTransformers, emitOnly), + emitOnly, + /*onlyBuildInfo*/ + false, + forceDtsEmit + ) ); mark("afterEmit"); measure("Emit", "beforeEmit", "afterEmit"); @@ -119936,7 +120099,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (skipTypeChecking(sourceFile, options, program)) { return emptyArray; } - const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + const programDiagnosticsInFile = updateAndGetProgramDiagnostics().getDiagnostics(sourceFile.fileName); if (!((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { return programDiagnosticsInFile; } @@ -119988,15 +120151,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); - const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false; - const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */ || isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); - let bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; - let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker2.getDiagnostics(sourceFile, cancellationToken) : emptyArray; + let bindDiagnostics = sourceFile.bindDiagnostics; + let checkDiagnostics = typeChecker2.getDiagnostics(sourceFile, cancellationToken); if (isPlainJs) { bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code)); checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code)); } - return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0); + return getMergedBindAndCheckDiagnostics(sourceFile, !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0); }); } function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, ...allDiagnostics) { @@ -120283,16 +120444,15 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getOptionsDiagnostics() { return sortAndDeduplicateDiagnostics(concatenate( - programDiagnostics.getGlobalDiagnostics(), + updateAndGetProgramDiagnostics().getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile() )); } function getOptionsDiagnosticsOfConfigFile() { - if (!options.configFile) - return emptyArray; - let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + if (!options.configFile) return emptyArray; + let diagnostics = updateAndGetProgramDiagnostics().getDiagnostics(options.configFile.fileName); forEachResolvedProjectReference2((resolvedRef) => { - diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + diagnostics = concatenate(diagnostics, updateAndGetProgramDiagnostics().getDiagnostics(resolvedRef.sourceFile.fileName)); }); return diagnostics; } @@ -120325,9 +120485,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config void 0, /*importClause*/ void 0, - externalHelpersModuleReference, - /*attributes*/ - void 0 + externalHelpersModuleReference ); addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */); setParent(externalHelpersModuleReference, importDecl); @@ -120345,7 +120503,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let imports; let moduleAugmentations; let ambientModules; - if ((getIsolatedModules(options) || isExternalModuleFile) && !file.isDeclarationFile) { + if (isJavaScriptFile || !file.isDeclarationFile && (getIsolatedModules(options) || isExternalModule(file))) { if (options.importHelpers) { imports = [createSyntheticImport(externalHelpersModuleNameText, file)]; } @@ -120466,7 +120624,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getLibFileFromReference(ref) { var _a2; - const { libFileName } = getLibFileNameFromLibReference(ref); + const libFileName = getLibFileNameFromLibReference(ref); const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } @@ -120502,15 +120660,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return sourceFile; } else { const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile2(fileName); - if (sourceFileNoExtension) - return sourceFileNoExtension; + if (sourceFileNoExtension) return sourceFileNoExtension; if (fail && options.allowNonTsExtensions) { fail(Diagnostics.File_0_not_found, fileName); return void 0; } const sourceFileWithAddedExtension = forEach(supportedExtensions[0], (extension) => getSourceFile2(fileName + extension)); - if (fail && !sourceFileWithAddedExtension) - fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); + if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); return sourceFileWithAddedExtension; } } @@ -120585,27 +120741,30 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let source = getSourceOfProjectReferenceRedirect(path); if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && fileName.includes(nodeModulesPathPart)) { const realPath2 = toPath3(host.realpath(fileName)); - if (realPath2 !== path) - source = getSourceOfProjectReferenceRedirect(realPath2); + if (realPath2 !== path) source = getSourceOfProjectReferenceRedirect(realPath2); } if (source) { const file2 = isString(source) ? findSourceFile(source, isDefaultLib, ignoreNoDefaultLib, reason, packageId) : void 0; - if (file2) - addFileToFilesByName( - file2, - path, - fileName, - /*redirectedPath*/ - void 0 - ); + if (file2) addFileToFilesByName( + file2, + path, + fileName, + /*redirectedPath*/ + void 0 + ); return file2; } } const originalFileName = fileName; if (filesByName.has(path)) { const file2 = filesByName.get(path); - addFileIncludeReason(file2 || void 0, reason); - if (file2 && !(options.forceConsistentCasingInFileNames === false)) { + const addedReason = addFileIncludeReason( + file2 || void 0, + reason, + /*checkExisting*/ + true + ); + if (file2 && addedReason && !(options.forceConsistentCasingInFileNames === false)) { const checkedName = file2.fileName; const isRedirect = toPath3(checkedName) !== toPath3(fileName); if (isRedirect) { @@ -120637,7 +120796,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return file2 || void 0; } let redirectedPath; - if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) { + if (!useSourceOfProjectReferenceRedirect) { const redirectProject = getProjectReferenceRedirectProject(fileName); if (redirectProject) { if (redirectProject.commandLine.options.outFile) { @@ -120668,7 +120827,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const dupFile = createRedirectedSourceFile(fileFromPackageId, file, fileName, path, toPath3(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, fileName, redirectedPath); - addFileIncludeReason(dupFile, reason); + addFileIncludeReason( + dupFile, + reason, + /*checkExisting*/ + false + ); sourceFileToPackageName.set(path, packageIdToPackageName(packageId)); processingOtherFiles.push(dupFile); return dupFile; @@ -120686,7 +120850,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config file.originalFileName = originalFileName; file.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; file.packageJsonScope = sourceFileOptions.packageJsonScope; - addFileIncludeReason(file, reason); + addFileIncludeReason( + file, + reason, + /*checkExisting*/ + false + ); if (host.useCaseSensitiveFileNames()) { const pathLowerCase = toFileNameLowerCase(path); const existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -120710,12 +120879,16 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } else { processingOtherFiles.push(file); } + (filesWithReferencesProcessed ?? (filesWithReferencesProcessed = /* @__PURE__ */ new Set())).add(file.path); } return file; } - function addFileIncludeReason(file, reason) { - if (file) + function addFileIncludeReason(file, reason, checkExisting) { + if (file && (!checkExisting || !isReferencedFile(reason) || !(filesWithReferencesProcessed == null ? void 0 : filesWithReferencesProcessed.has(reason.file)))) { fileReasons.add(file.path, reason); + return true; + } + return false; } function addFileToFilesByName(file, path, fileName, redirectedPath) { if (redirectedPath) { @@ -120727,10 +120900,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function updateFilesByNameMap(fileName, path, file) { filesByName.set(path, file); - if (file !== void 0) - missingFileNames.delete(path); - else - missingFileNames.set(path, fileName); + if (file !== void 0) missingFileNames.delete(path); + else missingFileNames.set(path, fileName); } function getProjectReferenceRedirect(fileName) { const referencedProject = getProjectReferenceRedirectProject(fileName); @@ -120762,8 +120933,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return forEachResolvedProjectReference(resolvedProjectReferences, cb); } function getSourceOfProjectReferenceRedirect(path) { - if (!isDeclarationFileName(path)) - return void 0; + if (!isDeclarationFileName(path)) return void 0; if (mapFromToProjectReferenceRedirectSource === void 0) { mapFromToProjectReferenceRedirectSource = /* @__PURE__ */ new Map(); forEachResolvedProjectReference2((resolvedRef) => { @@ -120808,15 +120978,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function processTypeReferenceDirectives(file) { const typeDirectives = file.typeReferenceDirectives; - if (!typeDirectives.length) - return; + if (!typeDirectives.length) return; const resolutions = (resolvedTypeReferenceDirectiveNamesProcessing == null ? void 0 : resolvedTypeReferenceDirectiveNamesProcessing.get(file.path)) || resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file); const resolutionsInFile = createModeAwareCache(); (resolvedTypeReferenceDirectiveNames ?? (resolvedTypeReferenceDirectiveNames = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); for (let index = 0; index < typeDirectives.length; index++) { const ref = file.typeReferenceDirectives[index]; const resolvedTypeReferenceDirective = resolutions[index]; - const fileName = toFileNameLowerCase(ref.fileName); + const fileName = ref.fileName; resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); const mode = ref.resolutionMode || getDefaultResolutionModeForFile2(file); processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); @@ -120833,56 +121002,20 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (_b2 = tracing) == null ? void 0 : _b2.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason) { - var _a2; addResolutionDiagnostics(resolution); - const previousResolution = (_a2 = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode)) == null ? void 0 : _a2.resolvedTypeReferenceDirective; - if (previousResolution && previousResolution.primary) { - return; - } - let saveResolution = true; const { resolvedTypeReferenceDirective } = resolution; if (resolvedTypeReferenceDirective) { - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth++; - if (resolvedTypeReferenceDirective.primary) { - processSourceFile( - resolvedTypeReferenceDirective.resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - resolvedTypeReferenceDirective.packageId, - reason - ); - } else { - if (previousResolution) { - if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { - const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - const existingFile = getSourceFile(previousResolution.resolvedFileName); - if (otherFileText !== existingFile.text) { - addFilePreprocessingFileExplainingDiagnostic( - existingFile, - reason, - Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, - [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName] - ); - } - } - saveResolution = false; - } else { - processSourceFile( - resolvedTypeReferenceDirective.resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - resolvedTypeReferenceDirective.packageId, - reason - ); - } - } - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth--; + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; + processSourceFile( + resolvedTypeReferenceDirective.resolvedFileName, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + resolvedTypeReferenceDirective.packageId, + reason + ); + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; } else { addFilePreprocessingFileExplainingDiagnostic( /*file*/ @@ -120892,14 +121025,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config [typeReferenceDirective] ); } - if (saveResolution) { - resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolution); - } } function pathForLibFile(libFileName) { const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); - if (existing) - return existing.actual; + if (existing) return existing.actual; const result = pathForLibFileWorker(libFileName); (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); return result.actual; @@ -120907,8 +121036,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function pathForLibFileWorker(libFileName) { var _a2, _b2, _c2, _d2, _e2; const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); - if (existing) - return existing; + if (existing) return existing; if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); if (oldResolution) { @@ -120945,7 +121073,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const { libName, libFileName } = getLibFileNameFromLibReference(libReference); + const libFileName = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -120956,15 +121084,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config { kind: 7 /* LibReferenceDirective */, file: file.path, index } ); } else { - const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); - const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); - const diagnostic = suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0; - const args = suggestion ? [libName, suggestion] : [libName]; (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({ - kind: 0 /* FilePreprocessingReferencedDiagnostic */, - reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index }, - diagnostic, - args + kind: 0 /* FilePreprocessingLibReferenceDiagnostic */, + reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index } }); } }); @@ -120991,7 +121113,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config continue; } const isFromNodeModulesSearch = resolution.isExternalLibraryImport; - const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension); + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension) && !getProjectReferenceRedirectProject(resolution.resolvedFileName); const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile && (!resolution.originalPath || pathContainsNodeModules(resolution.resolvedFileName)); const resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -121025,7 +121147,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!sourceFile.isDeclarationFile) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - addProgramDiagnosticExplainingFile( + addLazyProgramDiagnosticExplainingFile( sourceFile, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory] @@ -121155,7 +121277,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const rootPaths = new Set(rootNames.map(toPath3)); for (const file of files) { if (sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) { - addProgramDiagnosticExplainingFile( + addLazyProgramDiagnosticExplainingFile( file, Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, [file.fileName, options.configFilePath || ""] @@ -121286,6 +121408,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); } } + if (options.noCheck) { + if (options.noEmit) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noCheck", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } @@ -121510,31 +121637,85 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config }); } function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) { - var _a2; + let seenReasons; + const reasons = file && fileReasons.get(file.path); let fileIncludeReasons; let relatedInfo; let locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : void 0; - if (file) - (_a2 = fileReasons.get(file.path)) == null ? void 0 : _a2.forEach(processReason); - if (fileProcessingReason) - processReason(fileProcessingReason); - if (locationReason && (fileIncludeReasons == null ? void 0 : fileIncludeReasons.length) === 1) - fileIncludeReasons = void 0; + let fileIncludeReasonDetails; + let redirectInfo; + let cachedChain = file && (fileReasonsToChain == null ? void 0 : fileReasonsToChain.get(file.path)); + let chain; + if (cachedChain) { + if (cachedChain.fileIncludeReasonDetails) { + seenReasons = new Set(reasons); + reasons == null ? void 0 : reasons.forEach(populateRelatedInfo); + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + } + redirectInfo = cachedChain.redirectInfo; + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, getCompilerOptionsForFile(file)); + } + if (fileProcessingReason) processReason(fileProcessingReason); + const processedExtraReason = (seenReasons == null ? void 0 : seenReasons.size) !== (reasons == null ? void 0 : reasons.length); + if (locationReason && (seenReasons == null ? void 0 : seenReasons.size) === 1) seenReasons = void 0; + if (seenReasons && cachedChain) { + if (cachedChain.details && !processedExtraReason) { + chain = chainDiagnosticMessages(cachedChain.details, diagnostic, ...args || emptyArray); + } else if (cachedChain.fileIncludeReasonDetails) { + if (!processedExtraReason) { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasonDetails = cachedChain.fileIncludeReasonDetails; + } else { + fileIncludeReasons = cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length); + } + } else { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasons = [...cachedChain.fileIncludeReasonDetails.next, fileIncludeReasons[0]]; + } else { + fileIncludeReasons = append(cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length), fileIncludeReasons[0]); + } + } + } + } + if (!chain) { + if (!fileIncludeReasonDetails) fileIncludeReasonDetails = seenReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); + chain = chainDiagnosticMessages( + redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, + diagnostic, + ...args || emptyArray + ); + } + if (file) { + if (cachedChain) { + if (!cachedChain.fileIncludeReasonDetails || !processedExtraReason && fileIncludeReasonDetails) { + cachedChain.fileIncludeReasonDetails = fileIncludeReasonDetails; + } + } else { + (fileReasonsToChain ?? (fileReasonsToChain = /* @__PURE__ */ new Map())).set(file.path, cachedChain = { fileIncludeReasonDetails, redirectInfo }); + } + if (!cachedChain.details && !processedExtraReason) cachedChain.details = chain.next; + } const location = locationReason && getReferencedFileLocation(program, locationReason); - const fileIncludeReasonDetails = fileIncludeReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); - const optionsForFile = file && getCompilerOptionsForFile(file) || options; - const redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, optionsForFile); - const chain = chainDiagnosticMessages(redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, diagnostic, ...args || emptyArray); return location && isReferenceFileLocation(location) ? createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : createCompilerDiagnosticFromMessageChain(chain, relatedInfo); function processReason(reason) { - (fileIncludeReasons || (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason)); + if (seenReasons == null ? void 0 : seenReasons.has(reason)) return; + (seenReasons ?? (seenReasons = /* @__PURE__ */ new Set())).add(reason); + (fileIncludeReasons ?? (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason)); + populateRelatedInfo(reason); + } + function populateRelatedInfo(reason) { if (!locationReason && isReferencedFile(reason)) { locationReason = reason; } else if (locationReason !== reason) { - relatedInfo = append(relatedInfo, fileIncludeReasonToRelatedInformation(reason)); + relatedInfo = append(relatedInfo, getFileIncludeReasonToRelatedInformation(reason)); } - if (reason === fileProcessingReason) - fileProcessingReason = void 0; + } + function cachedFileIncludeDetailsHasProcessedExtraReason() { + var _a2; + return ((_a2 = cachedChain.fileIncludeReasonDetails.next) == null ? void 0 : _a2.length) !== (reasons == null ? void 0 : reasons.length); } } function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) { @@ -121546,14 +121727,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config args }); } - function addProgramDiagnosticExplainingFile(file, diagnostic, args) { - programDiagnostics.add(createDiagnosticExplainingFile( - file, - /*fileProcessingReason*/ - void 0, - diagnostic, - args - )); + function addLazyProgramDiagnosticExplainingFile(file, diagnostic, args) { + lazyProgramDiagnosticExplainingFile.push({ file, diagnostic, args }); + } + function getFileIncludeReasonToRelatedInformation(reason) { + let relatedInfo = reasonToRelatedInfo == null ? void 0 : reasonToRelatedInfo.get(reason); + if (relatedInfo === void 0) (reasonToRelatedInfo ?? (reasonToRelatedInfo = /* @__PURE__ */ new Map())).set(reason, relatedInfo = fileIncludeReasonToRelatedInformation(reason) ?? false); + return relatedInfo || void 0; } function fileIncludeReasonToRelatedInformation(reason) { if (isReferencedFile(reason)) { @@ -121582,14 +121762,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config message2 ) : void 0; } - if (!options.configFile) - return void 0; + if (!options.configFile) return void 0; let configFileNode; let message; switch (reason.kind) { case 0 /* RootFile */: - if (!options.configFile.configFileSpecs) - return void 0; + if (!options.configFile.configFileSpecs) return void 0; const fileName = getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory); const matchedByFiles = getMatchedFileSpec(program, fileName); if (matchedByFiles) { @@ -121598,8 +121776,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config break; } const matchedByInclude = getMatchedIncludeSpec(program, fileName); - if (!matchedByInclude || !isString(matchedByInclude)) - return void 0; + if (!matchedByInclude || !isString(matchedByInclude)) return void 0; configFileNode = getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = Diagnostics.File_is_matched_by_include_pattern_specified_here; break; @@ -121607,8 +121784,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 2 /* OutputFromProjectReference */: const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]); const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent == null ? void 0 : parent.sourceFile) || options.configFile, index: index2 } : void 0); - if (!referenceInfo) - return void 0; + if (!referenceInfo) return void 0; const { sourceFile, index } = referenceInfo; const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( @@ -121617,8 +121793,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here ) : void 0; case 8 /* AutomaticTypeDirectiveFile */: - if (!options.types) - return void 0; + if (!options.types) return void 0; configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference); message = Diagnostics.File_is_entry_point_of_type_library_specified_here; break; @@ -121655,10 +121830,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!options2.composite || options2.noEmit) { const inputs = parent ? parent.commandLine.fileNames : rootNames; if (inputs.length) { - if (!options2.composite) - createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - if (options2.noEmit) - createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); + if (!options2.composite) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + if (options2.noEmit) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); } } if (!parent && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) { @@ -121895,8 +122068,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { const originalDirectoryExists = host.compilerHost.directoryExists; const originalGetDirectories = host.compilerHost.getDirectories; const originalRealpath = host.compilerHost.realpath; - if (!host.useSourceOfProjectReferenceRedirect) - return { onProgramCreateComplete: noop, fileExists }; + if (!host.useSourceOfProjectReferenceRedirect) return { onProgramCreateComplete: noop, fileExists }; host.compilerHost.fileExists = fileExists; let directoryExists; if (originalDirectoryExists) { @@ -121905,8 +122077,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { handleDirectoryCouldBeSymlink(path); return true; } - if (!host.getResolvedProjectReferences()) - return false; + if (!host.getResolvedProjectReferences()) return false; if (!setOfDeclarationDirectories) { setOfDeclarationDirectories = /* @__PURE__ */ new Set(); host.forEachResolvedProjectReference((ref) => { @@ -121944,12 +122115,9 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { host.compilerHost.getDirectories = originalGetDirectories; } function fileExists(file) { - if (originalFileExists.call(host.compilerHost, file)) - return true; - if (!host.getResolvedProjectReferences()) - return false; - if (!isDeclarationFileName(file)) - return false; + if (originalFileExists.call(host.compilerHost, file)) return true; + if (!host.getResolvedProjectReferences()) return false; + if (!isDeclarationFileName(file)) return false; return fileOrDirectoryExistsUsingSource( file, /*isFile*/ @@ -121972,14 +122140,11 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) - return; - if (!originalRealpath || !directory.includes(nodeModulesPathPart)) - return; + if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; + if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return; const symlinkCache = host.getSymlinkCache(); const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); - if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) - return; + if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) return; const real = normalizePath(originalRealpath.call(host.compilerHost, directory)); let realPath2; if (real === directory || (realPath2 = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { @@ -121995,22 +122160,17 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { var _a; const fileOrDirectoryExistsUsingSource2 = isFile ? (file) => fileExistsIfProjectReferenceDts(file) : (dir) => directoryExistsIfProjectReferenceDeclDir(dir); const result = fileOrDirectoryExistsUsingSource2(fileOrDirectory); - if (result !== void 0) - return result; + if (result !== void 0) return result; const symlinkCache = host.getSymlinkCache(); const symlinkedDirectories = symlinkCache.getSymlinkedDirectories(); - if (!symlinkedDirectories) - return false; + if (!symlinkedDirectories) return false; const fileOrDirectoryPath = host.toPath(fileOrDirectory); - if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) - return false; - if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) - return true; + if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false; + if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) return true; return firstDefinedIterator( symlinkedDirectories.entries(), ([directoryPath, symlinkedDirectory]) => { - if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) - return void 0; + if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) return void 0; const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); if (isFile && result2) { const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); @@ -122031,8 +122191,7 @@ function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) program.getSemanticDiagnostics(sourceFile, cancellationToken); return sourceFile || options.outFile ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); } - if (!options.noEmitOnError) - return void 0; + if (!options.noEmitOnError) return void 0; let diagnostics = [ ...program.getOptionsDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), @@ -122046,13 +122205,11 @@ function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) cancellationToken ); } - if (!diagnostics.length) - return void 0; + if (!diagnostics.length) return void 0; let emittedFiles; if (!sourceFile && !options.outFile) { const emitResult = program.emitBuildInfo(writeFile2, cancellationToken); - if (emitResult.diagnostics) - diagnostics = [...diagnostics, ...emitResult.diagnostics]; + if (emitResult.diagnostics) diagnostics = [...diagnostics, ...emitResult.diagnostics]; emittedFiles = emitResult.emittedFiles; } return { diagnostics, sourceMaps: void 0, emittedFiles, emitSkipped: true }; @@ -122125,13 +122282,11 @@ function getModuleNames({ imports, moduleAugmentations }) { return res; } function getModuleNameStringLiteralAt({ imports, moduleAugmentations }, index) { - if (index < imports.length) - return imports[index]; + if (index < imports.length) return imports[index]; let augIndex = imports.length; for (const aug of moduleAugmentations) { if (aug.kind === 11 /* StringLiteral */) { - if (index === augIndex) - return aug; + if (index === augIndex) return aug; augIndex++; } } @@ -122147,6 +122302,7 @@ var BuilderState; getKeys: (v) => reverse.get(v), getValues: (k) => forward.get(k), keys: () => forward.keys(), + size: () => forward.size, deleteKey: (k) => { (deleted || (deleted = /* @__PURE__ */ new Set())).add(k); const set = forward.get(k); @@ -122242,11 +122398,9 @@ var BuilderState; if (sourceFile.moduleAugmentations.length) { const checker = program.getTypeChecker(); for (const moduleName of sourceFile.moduleAugmentations) { - if (!isStringLiteral(moduleName)) - continue; + if (!isStringLiteral(moduleName)) continue; const symbol = checker.getSymbolAtLocation(moduleName); - if (!symbol) - continue; + if (!symbol) continue; addReferenceFromAmbientModule(symbol); } } @@ -122275,12 +122429,15 @@ var BuilderState; return oldState && !oldState.referencedMap === !newReferencedMap; } BuilderState2.canReuseOldState = canReuseOldState; + function createReferencedMap(options) { + return options.module !== 0 /* None */ && !options.outFile ? createManyToManyPathMap() : void 0; + } + BuilderState2.createReferencedMap = createReferencedMap; function create(newProgram, oldState, disableUseFileVersionAsSignature) { var _a, _b; const fileInfos = /* @__PURE__ */ new Map(); const options = newProgram.getCompilerOptions(); - const isOutFile = options.outFile; - const referencedMap = options.module !== 0 /* None */ && !isOutFile ? createManyToManyPathMap() : void 0; + const referencedMap = createReferencedMap(options); const useOldState = canReuseOldState(referencedMap, oldState); newProgram.getTypeChecker(); for (const sourceFile of newProgram.getSourceFiles()) { @@ -122297,7 +122454,7 @@ var BuilderState; version: version2, signature, // No need to calculate affectsGlobalScope with --out since its not used at all - affectsGlobalScope: !isOutFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0, + affectsGlobalScope: !options.outFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0, impliedFormat: sourceFile.impliedNodeFormat }); } @@ -122370,22 +122527,19 @@ var BuilderState; BuilderState2.computeDtsSignature = computeDtsSignature; function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host, useFileVersionAsSignature = state.useFileVersionAsSignature) { var _a; - if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) - return false; + if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) return false; const info = state.fileInfos.get(sourceFile.resolvedPath); const prevSignature = info.signature; let latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, (signature) => { latestSignature = signature; - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 0 /* ComputedDts */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 0 /* ComputedDts */); }); } if (latestSignature === void 0) { latestSignature = sourceFile.version; - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 2 /* UsedVersion */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 2 /* UsedVersion */); } (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, prevSignature || false); (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(sourceFile.resolvedPath); @@ -122452,8 +122606,7 @@ var BuilderState; return state.allFilesExcludingDefaultLibraryFile; } let result; - if (firstSourceFile) - addSourceFile(firstSourceFile); + if (firstSourceFile) addSourceFile(firstSourceFile); for (const sourceFile of programOfThisState.getSourceFiles()) { if (sourceFile !== firstSourceFile) { addSourceFile(sourceFile); @@ -122503,31 +122656,22 @@ var BuilderState; // src/compiler/builder.ts function getBuilderFileEmit(options) { let result = 1 /* Js */; - if (options.sourceMap) - result = result | 2 /* JsMap */; - if (options.inlineSourceMap) - result = result | 4 /* JsInlineMap */; - if (getEmitDeclarations(options)) - result = result | 8 /* Dts */; - if (options.declarationMap) - result = result | 16 /* DtsMap */; - if (options.emitDeclarationOnly) - result = result & 24 /* AllDts */; + if (options.sourceMap) result = result | 2 /* JsMap */; + if (options.inlineSourceMap) result = result | 4 /* JsInlineMap */; + if (getEmitDeclarations(options)) result = result | 8 /* Dts */; + if (options.declarationMap) result = result | 16 /* DtsMap */; + if (options.emitDeclarationOnly) result = result & 24 /* AllDts */; return result; } function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) { const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind)); const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind); - if (oldEmitKind === emitKind) - return 0 /* None */; - if (!oldEmitKind || !emitKind) - return emitKind; + if (oldEmitKind === emitKind) return 0 /* None */; + if (!oldEmitKind || !emitKind) return emitKind; const diff = oldEmitKind ^ emitKind; let result = 0 /* None */; - if (diff & 7 /* AllJs */) - result = emitKind & 7 /* AllJs */; - if (diff & 24 /* AllDts */) - result = result | emitKind & 24 /* AllDts */; + if (diff & 7 /* AllJs */) result = emitKind & 7 /* AllJs */; + if (diff & 24 /* AllDts */) result = result | emitKind & 24 /* AllDts */; return result; } function hasSameKeys(map1, map2) { @@ -122587,19 +122731,17 @@ function createBuilderProgramState(newProgram, oldState) { if (emitDiagnostics) { (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set( sourceFilePath, - oldState.hasReusableDiagnostic ? convertToDiagnostics(emitDiagnostics, newProgram) : repopulateDiagnostics(emitDiagnostics, newProgram) + oldState.hasReusableDiagnostic ? convertToDiagnostics(emitDiagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(emitDiagnostics, newProgram) ); } if (canCopySemanticDiagnostics) { - if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) - return; - if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) - return; + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) return; + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set( sourceFilePath, - oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(diagnostics, newProgram) ); (state.semanticDiagnosticsFromOldState ?? (state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set())).add(sourceFilePath); } @@ -122613,10 +122755,8 @@ function createBuilderProgramState(newProgram, oldState) { } }); if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath) => { - if (state.fileInfos.has(sourceFilePath)) - return false; - if (outFilePath || info.affectsGlobalScope) - return true; + if (state.fileInfos.has(sourceFilePath)) return false; + if (outFilePath || info.affectsGlobalScope) return true; state.buildInfoEmitPending = true; return false; })) { @@ -122664,11 +122804,9 @@ function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) ); } function repopulateDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return diagnostics; + if (!diagnostics.length) return diagnostics; return sameMap(diagnostics, (diag2) => { - if (isString(diag2.messageText)) - return diag2; + if (isString(diag2.messageText)) return diag2; const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { var _a; return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); @@ -122690,18 +122828,17 @@ function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); } -function convertToDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return emptyArray; +function convertToDiagnostics(diagnostics, diagnosticFilePath, newProgram) { + if (!diagnostics.length) return emptyArray; let buildInfoDirectory; return diagnostics.map((diagnostic) => { - const result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory); + const result = convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportsDeprecated = diagnostic.reportDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; const { relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; return result; }); function toPathInBuildInfoDirectory(path) { @@ -122709,9 +122846,9 @@ function convertToDiagnostics(diagnostics, newProgram) { return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName); } } -function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { +function convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPath3) { const { file } = diagnostic; - const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; + const sourceFile = file !== false ? newProgram.getSourceFileByPath(file ? toPath3(file) : diagnosticFilePath) : void 0; return { ...diagnostic, file: sourceFile, @@ -122748,8 +122885,7 @@ function restoreBuilderProgramEmitState(state, savedEmitState) { state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; state.buildInfoEmitPending = savedEmitState.buildInfoEmitPending; state.emitDiagnosticsPerFile = savedEmitState.emitDiagnosticsPerFile; - if (savedEmitState.changedFilesSet) - state.changedFilesSet = savedEmitState.changedFilesSet; + if (savedEmitState.changedFilesSet) state.changedFilesSet = savedEmitState.changedFilesSet; } function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); @@ -122800,28 +122936,22 @@ function getNextAffectedFile(state, cancellationToken, host) { ); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; - if (!state.seenAffectedFiles) - state.seenAffectedFiles = /* @__PURE__ */ new Set(); + if (!state.seenAffectedFiles) state.seenAffectedFiles = /* @__PURE__ */ new Set(); } } function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles) { var _a; - if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) - return; - if (!emitOnlyDtsFiles) - return state.affectedFilesPendingEmit = void 0; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return; + if (!emitOnlyDtsFiles) return state.affectedFilesPendingEmit = void 0; state.affectedFilesPendingEmit.forEach((emitKind, path) => { const pending = emitKind & 7 /* AllJs */; - if (!pending) - state.affectedFilesPendingEmit.delete(path); - else - state.affectedFilesPendingEmit.set(path, pending); + if (!pending) state.affectedFilesPendingEmit.delete(path); + else state.affectedFilesPendingEmit.set(path, pending); }); } function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { var _a; - if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) - return void 0; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => { var _a2; const affectedFile = state.program.getSourceFileByPath(path); @@ -122831,16 +122961,13 @@ function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { } const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath); let pendingKind = getPendingEmitKind(emitKind, seenKind); - if (emitOnlyDtsFiles) - pendingKind = pendingKind & 24 /* AllDts */; - if (pendingKind) - return { affectedFile, emitKind: pendingKind }; + if (emitOnlyDtsFiles) pendingKind = pendingKind & 24 /* AllDts */; + if (pendingKind) return { affectedFile, emitKind: pendingKind }; }); } function getNextPendingEmitDiagnosticsFile(state) { var _a; - if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) - return void 0; + if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.emitDiagnosticsPerFile, (diagnostics, path) => { var _a2; const affectedFile = state.program.getSourceFileByPath(path); @@ -122849,8 +122976,7 @@ function getNextPendingEmitDiagnosticsFile(state) { return void 0; } const seenKind = ((_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath)) || 0 /* None */; - if (!(seenKind & 24 /* AllDts */)) - return { affectedFile, diagnostics, seenKind }; + if (!(seenKind & 24 /* AllDts */)) return { affectedFile, diagnostics, seenKind }; }); } function removeDiagnosticsOfLibraryFiles(state) { @@ -122874,8 +123000,7 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken ); return; } - if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) - return; + if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; handleDtsMayChangeOfReferencingExportOfAffectedFile( state, affectedFile, @@ -122883,7 +123008,7 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken host ); } -function handleDtsMayChangeOf(state, path, cancellationToken, host) { +function handleDtsMayChangeOf(state, path, invalidateJsFiles, cancellationToken, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { const program = Debug.checkDefined(state.program); @@ -122898,7 +123023,9 @@ function handleDtsMayChangeOf(state, path, cancellationToken, host) { /*useFileVersionAsSignature*/ true ); - if (getEmitDeclarations(state.compilerOptions)) { + if (invalidateJsFiles) { + addToAffectedFilesPendingEmit(state, path, getBuilderFileEmit(state.compilerOptions)); + } else if (getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, state.compilerOptions.declarationMap ? 24 /* AllDts */ : 8 /* Dts */); } } @@ -122917,10 +123044,9 @@ function isChangedSignature(state, path) { const newSignature = Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } -function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host) { +function handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host) { var _a; - if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) - return false; + if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) return false; BuilderState.getAllFilesExcludingDefaultLibraryFile( state, state.program, @@ -122930,6 +123056,7 @@ function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, hos (file) => handleDtsMayChangeOf( state, file.resolvedPath, + invalidateJsFiles, cancellationToken, host ) @@ -122938,11 +123065,9 @@ function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, hos return true; } function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) { - var _a; - if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) - return; - if (!isChangedSignature(state, affectedFile.resolvedPath)) - return; + var _a, _b; + if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; + if (!isChangedSignature(state, affectedFile.resolvedPath)) return; if (getIsolatedModules(state.compilerOptions)) { const seenFileNamesMap = /* @__PURE__ */ new Map(); seenFileNamesMap.set(affectedFile.resolvedPath, true); @@ -122951,9 +123076,22 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile const currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, host)) - return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, host); + if (handleDtsMayChangeOfGlobalScope( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + )) return; + handleDtsMayChangeOf( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + ); if (isChangedSignature(state, currentPath)) { const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -122962,30 +123100,38 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile } } const seenFileAndExportsOfFile = /* @__PURE__ */ new Set(); - (_a = state.referencedMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _a.forEach((exportedFromPath) => { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) - return true; + const invalidateJsFiles = !!((_a = affectedFile.symbol) == null ? void 0 : _a.exports) && !!forEachEntry( + affectedFile.symbol.exports, + (exported) => { + if ((exported.flags & 128 /* ConstEnum */) !== 0) return true; + const aliased = skipAlias(exported, state.program.getTypeChecker()); + if (aliased === exported) return false; + return (aliased.flags & 128 /* ConstEnum */) !== 0 && some(aliased.declarations, (d) => getSourceFileOfNode(d) === affectedFile); + } + ); + (_b = state.referencedMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _b.forEach((exportedFromPath) => { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, invalidateJsFiles, cancellationToken, host)) return true; const references = state.referencedMap.getKeys(exportedFromPath); return references && forEachKey(references, (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( state, filePath, + invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host )); }); } -function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) { +function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host) { var _a; - if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) - return void 0; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host)) - return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, host); + if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return void 0; + if (handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host)) return true; + handleDtsMayChangeOf(state, filePath, invalidateJsFiles, cancellationToken, host); (_a = state.referencedMap.getKeys(filePath)) == null ? void 0 : _a.forEach( (referencingFilePath) => handleDtsMayChangeOfFileAndExportsOfFile( state, referencingFilePath, + invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host @@ -123018,12 +123164,13 @@ function isProgramBundleEmitBuildInfo(info) { return !!((_a = info.options) == null ? void 0 : _a.outFile); } function getBuildInfo2(state) { - var _a; + var _a, _b; const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory(); const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0; const fileNames = []; const fileNameToFileId = /* @__PURE__ */ new Map(); + const rootFileNames = new Set(state.program.getRootFileNames().map((f) => toPath(f, currentDirectory, state.program.getCanonicalFileName))); const root = []; if (state.compilerOptions.outFile) { const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => { @@ -123035,6 +123182,7 @@ function getBuildInfo2(state) { fileNames, fileInfos: fileInfos2, root, + resolvedRoot: toResolvedRoot(), options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), outSignature: state.outSignature, latestChangedDtsFile, @@ -123053,7 +123201,7 @@ function getBuildInfo2(state) { let fileNamesToFileIdListId; let emitSignatures; const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]) => { - var _a2, _b; + var _a2, _b2; const fileId = toFileId(key); tryAddRoot(key, fileId); Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); @@ -123062,9 +123210,10 @@ function getBuildInfo2(state) { if (state.compilerOptions.composite) { const file = state.program.getSourceFileByPath(key); if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) { - const emitSignature = (_b = state.emitSignatures) == null ? void 0 : _b.get(key); + const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key); if (emitSignature !== actualSignature) { - (emitSignatures || (emitSignatures = [])).push( + emitSignatures = append( + emitSignatures, emitSignature === void 0 ? fileId : ( // There is no emit, encode as false // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature @@ -123095,24 +123244,24 @@ function getBuildInfo2(state) { ); }); let referencedMap; - if (state.referencedMap) { + if ((_a = state.referencedMap) == null ? void 0 : _a.size()) { referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map((key) => [ toFileId(key), toFileIdListId(state.referencedMap.getValues(key)) ]); } - const semanticDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(state.semanticDiagnosticsPerFile); + const semanticDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(); let affectedFilesPendingEmit; - if ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size) { + if ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.size) { const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions); const seenFiles = /* @__PURE__ */ new Set(); for (const path of arrayFrom(state.affectedFilesPendingEmit.keys()).sort(compareStringsCaseSensitive)) { if (tryAddToSet(seenFiles, path)) { const file = state.program.getSourceFileByPath(path); - if (!file || !sourceFileMayBeEmitted(file, state.program)) - continue; + if (!file || !sourceFileMayBeEmitted(file, state.program)) continue; const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path); - (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push( + affectedFilesPendingEmit = append( + affectedFilesPendingEmit, pendingEmit === fullEmitForOptions ? fileId : ( // Pending full emit per options pendingEmit === 8 /* Dts */ ? [fileId] : ( @@ -123128,14 +123277,15 @@ function getBuildInfo2(state) { let changeFileSet; if (state.changedFilesSet.size) { for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { - (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + changeFileSet = append(changeFileSet, toFileId(path)); } } - const emitDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(state.emitDiagnosticsPerFile); + const emitDiagnosticsPerFile = convertToProgramBuildInfoEmitDiagnostics(); const program = { fileNames, fileInfos, root, + resolvedRoot: toResolvedRoot(), options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), fileIdsList, referencedMap, @@ -123166,29 +123316,34 @@ function getBuildInfo2(state) { const key = fileIds.join(); let fileIdListId = fileNamesToFileIdListId == null ? void 0 : fileNamesToFileIdListId.get(key); if (fileIdListId === void 0) { - (fileIdsList || (fileIdsList = [])).push(fileIds); - (fileNamesToFileIdListId || (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length); + fileIdsList = append(fileIdsList, fileIds); + (fileNamesToFileIdListId ?? (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length); } return fileIdListId; } function tryAddRoot(path, fileId) { const file = state.program.getSourceFile(path); - if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */)) - return; - if (!root.length) - return root.push(fileId); + if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */)) return; + if (!root.length) return root.push(fileId); const last2 = root[root.length - 1]; const isLastStartEnd = isArray(last2); - if (isLastStartEnd && last2[1] === fileId - 1) - return last2[1] = fileId; - if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1) - return root.push(fileId); + if (isLastStartEnd && last2[1] === fileId - 1) return last2[1] = fileId; + if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1) return root.push(fileId); const lastButOne = root[root.length - 2]; - if (!isNumber(lastButOne) || lastButOne !== last2 - 1) - return root.push(fileId); + if (!isNumber(lastButOne) || lastButOne !== last2 - 1) return root.push(fileId); root[root.length - 2] = [lastButOne, fileId]; return root.length = root.length - 1; } + function toResolvedRoot() { + let result; + rootFileNames.forEach((path) => { + const file = state.program.getSourceFileByPath(path); + if (file && path !== file.resolvedPath) { + result = append(result, [toFileId(file.resolvedPath), toFileId(path)]); + } + }); + return result; + } function convertToProgramBuildInfoCompilerOptions(options) { let result; const { optionsNameMap } = getOptionsNameMap(); @@ -123217,39 +123372,53 @@ function getBuildInfo2(state) { } return value; } - function convertToProgramBuildInfoDiagnostics(diagnostics) { + function convertToProgramBuildInfoDiagnostics() { let result; - if (diagnostics) { - for (const key of arrayFrom(diagnostics.keys()).sort(compareStringsCaseSensitive)) { - const value = diagnostics.get(key); - (result || (result = [])).push( - value.length ? [ - toFileId(key), - convertToReusableDiagnostics(value) - ] : toFileId(key) - ); + state.fileInfos.forEach((_value, key) => { + var _a2; + const value = (_a2 = state.semanticDiagnosticsPerFile) == null ? void 0 : _a2.get(key); + if (!value) { + if (!state.changedFilesSet.has(key)) result = append(result, toFileId(key)); + } else if (value.length) { + result = append(result, [ + toFileId(key), + convertToReusableDiagnostics(value, key) + ]); } + }); + return result; + } + function convertToProgramBuildInfoEmitDiagnostics() { + var _a2; + let result; + if (!((_a2 = state.emitDiagnosticsPerFile) == null ? void 0 : _a2.size)) return result; + for (const key of arrayFrom(state.emitDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) { + const value = state.emitDiagnosticsPerFile.get(key); + result = append(result, [ + toFileId(key), + convertToReusableDiagnostics(value, key) + ]); } return result; } - function convertToReusableDiagnostics(diagnostics) { + function convertToReusableDiagnostics(diagnostics, diagnosticFilePath) { Debug.assert(!!diagnostics.length); return diagnostics.map((diagnostic) => { - const result = convertToReusableDiagnosticRelatedInformation(diagnostic); + const result = convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportDeprecated = diagnostic.reportsDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; const { relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r)) : [] : void 0; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r, diagnosticFilePath)) : [] : void 0; return result; }); } - function convertToReusableDiagnosticRelatedInformation(diagnostic) { + function convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath) { const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + file: file ? file.resolvedPath === diagnosticFilePath ? void 0 : relativeToBuildInfo(file.resolvedPath) : false, messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } @@ -123264,12 +123433,10 @@ function getBuildInfo2(state) { return next === chain.next ? chain : { ...chain, next }; } function convertToReusableDiagnosticMessageChainArray(array) { - if (!array) - return array; + if (!array) return array; return forEach(array, (chain, index) => { const reusable = convertToReusableDiagnosticMessageChain(chain); - if (chain === reusable) - return void 0; + if (chain === reusable) return void 0; const result = index > 0 ? array.slice(0, index - 1) : []; result.push(reusable); for (let i = index + 1; i < array.length; i++) { @@ -123323,10 +123490,8 @@ function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n"); } function locationInfo(diagnostic) { - if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) - return `(${diagnostic.start},${diagnostic.length})`; - if (sourceFileDirectory === void 0) - sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) return `(${diagnostic.start},${diagnostic.length})`; + if (sourceFileDirectory === void 0) sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); return `${ensurePathIsNonModuleName(getRelativePathFromDirectory( sourceFileDirectory, diagnostic.file.resolvedPath, @@ -123394,8 +123559,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa affected: pendingForDiagnostics.affectedFile }; } - if (!state.buildInfoEmitPending) - return void 0; + if (!state.buildInfoEmitPending) return void 0; const affected2 = state.program; const result2 = affected2.emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken); state.buildInfoEmitPending = false; @@ -123403,21 +123567,16 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa } ({ affectedFile: affected, emitKind } = pendingAffectedFile); } else { - if (!state.programEmitPending) - return void 0; + if (!state.programEmitPending) return void 0; emitKind = state.programEmitPending; - if (emitOnlyDtsFiles) - emitKind = emitKind & 24 /* AllDts */; - if (!emitKind) - return void 0; + if (emitOnlyDtsFiles) emitKind = emitKind & 24 /* AllDts */; + if (!emitKind) return void 0; affected = state.program; } } let emitOnly; - if (emitKind & 7 /* AllJs */) - emitOnly = 0 /* Js */; - if (emitKind & 24 /* AllDts */) - emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; + if (emitKind & 7 /* AllJs */) emitOnly = 0 /* Js */; + if (emitKind & 24 /* AllDts */) emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; if (affected === state.program) { state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0; } @@ -123431,27 +123590,22 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa if (affected !== state.program) { const affectedSourceFile = affected; state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); - if (state.affectedFilesIndex !== void 0) - state.affectedFilesIndex++; + if (state.affectedFilesIndex !== void 0) state.affectedFilesIndex++; state.buildInfoEmitPending = true; const existing = ((_a = state.seenEmittedFiles) == null ? void 0 : _a.get(affectedSourceFile.resolvedPath)) || 0 /* None */; (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing); const existingPending = ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || programEmitKind; const pendingKind = getPendingEmitKind(existingPending, emitKind | existing); - if (pendingKind) - (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); - else - (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); - if (result.diagnostics.length) - (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); + if (pendingKind) (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); + else (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); + if (result.diagnostics.length) (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); } else { state.changedFilesSet.clear(); } return { result, affected }; } function getWriteFileCallback(writeFile2, customTransformers) { - if (!getEmitDeclarations(state.compilerOptions)) - return writeFile2 || maybeBind(host, host.writeFile); + if (!getEmitDeclarations(state.compilerOptions)) return writeFile2 || maybeBind(host, host.writeFile); return (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => { var _a, _b, _c; if (isDeclarationFileName(fileName)) { @@ -123469,15 +123623,12 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa host, data ); - if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) - emitSignature = signature; + if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) emitSignature = signature; if (signature !== file.version) { - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(file.resolvedPath, 1 /* StoredSignatureAtEmit */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(file.resolvedPath, 1 /* StoredSignatureAtEmit */); if (state.affectedFiles) { const existing = (_b = state.oldSignatures) == null ? void 0 : _b.get(file.resolvedPath); - if (existing === void 0) - (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); + if (existing === void 0) (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); info.signature = signature; } else { info.signature = signature; @@ -123488,8 +123639,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa if (state.compilerOptions.composite) { const filePath = sourceFiles[0].resolvedPath; emitSignature = handleNewSignature((_c = state.emitSignatures) == null ? void 0 : _c.get(filePath), emitSignature); - if (!emitSignature) - return; + if (!emitSignature) return; (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); } } else if (state.compilerOptions.composite) { @@ -123498,27 +123648,20 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa /*newSignature*/ void 0 ); - if (!newSignature) - return; + if (!newSignature) return; state.outSignature = newSignature; } } - if (writeFile2) - writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data); - else if (host.writeFile) - host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); - else - state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + if (writeFile2) writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else if (host.writeFile) host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); function handleNewSignature(oldSignatureFormat, newSignature) { const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0]; newSignature ?? (newSignature = computeSignature(text, host, data)); if (newSignature === oldSignature) { - if (oldSignatureFormat === oldSignature) - return void 0; - else if (data) - data.differsOnlyInMap = true; - else - data = { differsOnlyInMap: true }; + if (oldSignatureFormat === oldSignature) return void 0; + else if (data) data.differsOnlyInMap = true; + else data = { differsOnlyInMap: true }; } else { state.hasChangedEmitSignature = true; state.latestChangedDtsFile = fileName; @@ -123532,8 +123675,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); } const result = handleNoEmitOptions(builderProgram, targetSourceFile, writeFile2, cancellationToken); - if (result) - return result; + if (result) return result; if (!targetSourceFile) { if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { let sourceMaps = []; @@ -123569,8 +123711,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa while (true) { const affected = getNextAffectedFile(state, cancellationToken, host); let result; - if (!affected) - return void 0; + if (!affected) return void 0; else if (affected !== state.program) { const affectedSourceFile = affected; if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) { @@ -123579,8 +123720,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); state.affectedFilesIndex++; state.buildInfoEmitPending = true; - if (!result) - continue; + if (!result) continue; } else { result = state.program.getSemanticDiagnostics( /*sourceFile*/ @@ -123657,12 +123797,10 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos const path = toFilePath(index + 1); const stateFileInfo = toBuilderStateFileInfoForMultiEmit(fileInfo); fileInfos.set(path, stateFileInfo); - if (emitSignatures && stateFileInfo.signature) - emitSignatures.set(path, stateFileInfo.signature); + if (emitSignatures && stateFileInfo.signature) emitSignatures.set(path, stateFileInfo.signature); }); (_d = program.emitSignatures) == null ? void 0 : _d.forEach((value) => { - if (isNumber(value)) - emitSignatures.delete(toFilePath(value)); + if (isNumber(value)) emitSignatures.delete(toFilePath(value)); else { const key = toFilePath(value[0]); emitSignatures.set( @@ -123674,16 +123812,17 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos ); } }); + const changedFilesSet = new Set(map(program.changeFileSet, toFilePath)); const fullEmitForOptions = program.affectedFilesPendingEmit ? getBuilderFileEmit(program.options || {}) : void 0; state = { fileInfos, compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - semanticDiagnosticsPerFile: toPerFileDiagnostics(program.semanticDiagnosticsPerFile), - emitDiagnosticsPerFile: toPerFileDiagnostics(program.emitDiagnosticsPerFile), + referencedMap: toManyToManyPathMap(program.referencedMap, program.options ?? {}), + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(program.semanticDiagnosticsPerFile, fileInfos, changedFilesSet), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(program.emitDiagnosticsPerFile), hasReusableDiagnostic: true, affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), - changedFilesSet: new Set(map(program.changeFileSet, toFilePath)), + changedFilesSet, latestChangedDtsFile, emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0 }; @@ -123725,16 +123864,27 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos function toFilePathsSet(fileIdsListId) { return filePathsSetList[fileIdsListId - 1]; } - function toManyToManyPathMap(referenceMap) { - if (!referenceMap) { - return void 0; - } - const map2 = BuilderState.createManyToManyPathMap(); + function toManyToManyPathMap(referenceMap, options) { + const map2 = BuilderState.createReferencedMap(options); + if (!map2 || !referenceMap) return map2; referenceMap.forEach(([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); return map2; } - function toPerFileDiagnostics(diagnostics) { - return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => isNumber(value) ? emptyArray : value[1]); + function toPerFileSemanticDiagnostics(diagnostics, fileInfos, changedFilesSet) { + const semanticDiagnostics = new Map( + mapDefinedIterator( + fileInfos.keys(), + (key) => !changedFilesSet.has(key) ? [key, emptyArray] : void 0 + ) + ); + diagnostics == null ? void 0 : diagnostics.forEach((value) => { + if (isNumber(value)) semanticDiagnostics.delete(toFilePath(value)); + else semanticDiagnostics.set(toFilePath(value[0]), value[1]); + }); + return semanticDiagnostics.size ? semanticDiagnostics : void 0; + } + function toPerFileEmitDiagnostics(diagnostics) { + return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(value[0]), (value) => value[1]); } } function getBuildInfoFileVersionMap(program, buildInfoPath, host) { @@ -123742,7 +123892,8 @@ function getBuildInfoFileVersionMap(program, buildInfoPath, host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const fileInfos = /* @__PURE__ */ new Map(); let rootIndex = 0; - const roots = []; + const roots = /* @__PURE__ */ new Map(); + const resolvedRoots = new Map(program.resolvedRoot); program.fileInfos.forEach((fileInfo, index) => { const path = toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); const version2 = isString(fileInfo) ? fileInfo : fileInfo.version; @@ -123752,17 +123903,24 @@ function getBuildInfoFileVersionMap(program, buildInfoPath, host) { const fileId = index + 1; if (isArray(current)) { if (current[0] <= fileId && fileId <= current[1]) { - roots.push(path); - if (current[1] === fileId) - rootIndex++; + addRoot(fileId, path); + if (current[1] === fileId) rootIndex++; } } else if (current === fileId) { - roots.push(path); + addRoot(fileId, path); rootIndex++; } } }); return { fileInfos, roots }; + function addRoot(fileId, path) { + const root = resolvedRoots.get(fileId); + if (root) { + roots.set(toPath(program.fileNames[root - 1], buildInfoDirectory, getCanonicalFileName), path); + } else { + roots.set(path, void 0); + } + } } function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { @@ -123805,14 +123963,12 @@ function removeIgnoredPath(path) { return some(ignoredPaths, (searchPath) => path.includes(searchPath)) ? void 0 : path; } function perceivedOsRootLengthForWatching(pathComponents2, length2) { - if (length2 <= 1) - return 1; + if (length2 <= 1) return 1; let indexAfterOsRoot = 1; let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0; if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) { - if (length2 === 2) - return 2; + if (length2 === 2) return 2; indexAfterOsRoot = 2; isDosStyle = true; } @@ -123825,10 +123981,8 @@ function perceivedOsRootLengthForWatching(pathComponents2, length2) { return indexAfterOsRoot + 2; } function canWatchDirectoryOrFile(pathComponents2, length2) { - if (length2 === void 0) - length2 = pathComponents2.length; - if (length2 <= 2) - return false; + if (length2 === void 0) length2 = pathComponents2.length; + if (length2 <= 2) return false; const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2); return length2 > perceivedOsRootLength + 1; } @@ -123836,11 +123990,9 @@ function canWatchAtTypes(atTypes) { return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes)); } function isInDirectoryPath(dirComponents, fileOrDirComponents) { - if (fileOrDirComponents.length < fileOrDirComponents.length) - return false; + if (fileOrDirComponents.length < fileOrDirComponents.length) return false; for (let i = 0; i < dirComponents.length; i++) { - if (fileOrDirComponents[i] !== dirComponents[i]) - return false; + if (fileOrDirComponents[i] !== dirComponents[i]) return false; } return true; } @@ -123855,11 +124007,9 @@ function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLoo failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); const failedLookupComponents = getPathComponents(failedLookupLocation); const perceivedOsRootLength = perceivedOsRootLengthForWatching(failedLookupPathComponents, failedLookupPathComponents.length); - if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) - return void 0; + if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) return void 0; const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules"); - if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) - return void 0; + if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) return void 0; const lastNodeModulesIndex = failedLookupPathComponents.lastIndexOf("node_modules"); if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { if (failedLookupPathComponents.length > rootPathComponents.length + 1) { @@ -124196,10 +124346,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW fileWatchesOfAffectingLocations.get(existing[i]).files--; } } - if (expected) - impliedFormatPackageJsons.set(newFile.resolvedPath, newFile.packageJsonLocations); - else - impliedFormatPackageJsons.delete(newFile.resolvedPath); + if (expected) impliedFormatPackageJsons.set(newFile.resolvedPath, newFile.packageJsonLocations); + else impliedFormatPackageJsons.delete(newFile.resolvedPath); }); impliedFormatPackageJsons.forEach((existing, path) => { const newFile = newProgram == null ? void 0 : newProgram.getSourceFileByPath(path); @@ -124420,8 +124568,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW /*mode*/ void 0 ); - if (resolution && !resolution.isInvalidated) - return resolution; + if (resolution && !resolution.isInvalidated) return resolution; const data = (_a = resolutionHost.beforeResolveSingleModuleNameWithoutWatching) == null ? void 0 : _a.call(resolutionHost, moduleResolutionCache); const host = getModuleResolutionHost(resolutionHost); const result = resolveModuleName( @@ -124454,8 +124601,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if (resolved && resolved.resolvedFileName) { const key = resolutionHost.toPath(resolved.resolvedFileName); let resolutions = resolvedFileToResolution.get(key); - if (!resolutions) - resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); + if (!resolutions) resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); resolutions.add(resolution); } } @@ -124486,18 +124632,15 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); const { failedLookupLocations, affectingLocations, alternateResult } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) - return; - if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) - resolutionsWithFailedLookups.add(resolution); + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) return; + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - if (alternateResult) - setAtRoot = watchFailedLookupLocation(alternateResult, setAtRoot); + if (alternateResult) setAtRoot = watchFailedLookupLocation(alternateResult, setAtRoot); if (setAtRoot) { setDirectoryWatcher( rootDir, @@ -124515,10 +124658,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); const { affectingLocations } = resolution; - if (!(affectingLocations == null ? void 0 : affectingLocations.length)) - return; - if (addToResolutionsWithOnlyAffectingLocations) - resolutionsWithOnlyAffectingLocations.add(resolution); + if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; + if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); for (const affectingLocation of affectingLocations) { createFileWatcherOfAffectingLocation( affectingLocation, @@ -124530,10 +124671,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { const fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); if (fileWatcher) { - if (forResolution) - fileWatcher.resolutions++; - else - fileWatcher.files++; + if (forResolution) fileWatcher.resolutions++; + else fileWatcher.files++; return; } let locationToWatch = affectingLocation; @@ -124560,8 +124699,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW symlinks: void 0 }; fileWatchesOfAffectingLocations.set(locationToWatch, watcher); - if (isSymlink) - symlinkWatcher = watcher; + if (isSymlink) symlinkWatcher = watcher; } if (isSymlink) { Debug.assert(!!symlinkWatcher); @@ -124587,10 +124725,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function invalidateAffectingFileWatcher(path, packageJsonMap) { var _a; const watcher = fileWatchesOfAffectingLocations.get(path); - if (watcher == null ? void 0 : watcher.resolutions) - (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); - if (watcher == null ? void 0 : watcher.files) - (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.resolutions) (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.files) (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); } @@ -124645,8 +124781,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW watcher: createDirPathToWatcher(), refCount: 1 }); - if (isSymlink) - dirPathToSymlinkPackageRefCount.set(dirPath, (dirPathToSymlinkPackageRefCount.get(dirPath) ?? 0) + 1); + if (isSymlink) dirPathToSymlinkPackageRefCount.set(dirPath, (dirPathToSymlinkPackageRefCount.get(dirPath) ?? 0) + 1); } function createDirPathToWatcher() { return isSymlink ? createOrAddRefToDirectoryWatchOfFailedLookups(packageDir, packageDirPath, nonRecursive) : createOrAddRefToDirectoryWatchOfFailedLookups(dir, dirPath, nonRecursive); @@ -124698,8 +124833,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW dirPathToSymlinkPackageRefCount.set(dirPath, refCount); } } - if (syncDirWatcherRemove) - closePackageDirWatcher(packageDirWatcher, packageDirPath); + if (syncDirWatcherRemove) closePackageDirWatcher(packageDirWatcher, packageDirPath); } } else { removeDirectoryWatcher(dirPath, syncDirWatcherRemove); @@ -124717,8 +124851,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if (resolved && resolved.resolvedFileName) { const key = resolutionHost.toPath(resolved.resolvedFileName); const resolutions = resolvedFileToResolution.get(key); - if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) - resolvedFileToResolution.delete(key); + if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } const { failedLookupLocations, affectingLocations, alternateResult } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { @@ -124728,10 +124861,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove); } } - if (alternateResult) - removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot, syncDirWatcherRemove); - if (removeAtRoot) - removeDirectoryWatcher(rootPath, syncDirWatcherRemove); + if (alternateResult) removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot, syncDirWatcherRemove); + if (removeAtRoot) removeDirectoryWatcher(rootPath, syncDirWatcherRemove); } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -124739,16 +124870,14 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW for (const affectingLocation of affectingLocations) { const watcher = fileWatchesOfAffectingLocations.get(affectingLocation); watcher.resolutions--; - if (syncDirWatcherRemove) - closeFileWatcherOfAffectingLocation(watcher, affectingLocation); + if (syncDirWatcherRemove) closeFileWatcherOfAffectingLocation(watcher, affectingLocation); } } } function removeDirectoryWatcher(dirPath, syncDirWatcherRemove) { const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); dirWatcher.refCount--; - if (syncDirWatcherRemove) - closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); + if (syncDirWatcherRemove) closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); } function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => { @@ -124774,14 +124903,11 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } } function removeResolutionsFromProjectReferenceRedirects(filePath) { - if (!fileExtensionIs(filePath, ".json" /* Json */)) - return; + if (!fileExtensionIs(filePath, ".json" /* Json */)) return; const program = resolutionHost.getCurrentProgram(); - if (!program) - return; + if (!program) return; const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); - if (!resolvedProjectReference) - return; + if (!resolvedProjectReference) return; resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); } function removeResolutionsOfFile(filePath, syncDirWatcherRemove) { @@ -124789,12 +124915,10 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective, syncDirWatcherRemove); } function invalidateResolutions(resolutions, canInvalidate) { - if (!resolutions) - return false; + if (!resolutions) return false; let invalidated = false; resolutions.forEach((resolution) => { - if (resolution.isInvalidated || !canInvalidate(resolution)) - return; + if (resolution.isInvalidated || !canInvalidate(resolution)) return; resolution.isInvalidated = invalidated = true; for (const containingFilePath of Debug.checkDefined(resolution.files)) { (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(containingFilePath); @@ -124819,8 +124943,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW (isInDirectoryChecks || (isInDirectoryChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); } else { const updatedPath = removeIgnoredPath(fileOrDirectoryPath); - if (!updatedPath) - return false; + if (!updatedPath) return false; fileOrDirectoryPath = updatedPath; if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) { return false; @@ -124842,8 +124965,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW /*isFolder*/ true ); - if (packagePath) - (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); + if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); @@ -124892,10 +125014,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } function canInvalidateFailedLookupResolution(resolution) { var _a; - if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) - return true; - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) - return false; + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.alternateResult && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.alternateResult)); } function isInvalidatedFailedLookup(locationPath) { @@ -124950,8 +125070,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } } function canWatchTypeRootPath(typeRoot) { - if (resolutionHost.getCompilationSettings().typeRoots) - return true; + if (resolutionHost.getCompilationSettings().typeRoots) return true; return canWatchAtTypes(resolutionHost.toPath(typeRoot)); } } @@ -125035,8 +125154,7 @@ function getErrorCountForSummary(diagnostics) { function getFilesInErrorForSummary(diagnostics) { const filesInError = filter(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */).map( (errorDiagnostic) => { - if (errorDiagnostic.file === void 0) - return; + if (errorDiagnostic.file === void 0) return; return `${errorDiagnostic.file.fileName}`; } ); @@ -125070,8 +125188,7 @@ function prettyPathForFileError(error, cwd) { return error.fileName + line; } function getErrorSummaryText(errorCount, filesInError, newLine, host) { - if (errorCount === 0) - return ""; + if (errorCount === 0) return ""; const nonNilFiles = filesInError.filter((fileInError) => fileInError !== void 0); const distinctFileNamesWithLines = nonNilFiles.map((fileInError) => `${fileInError.fileName}:${fileInError.line}`).filter((value, index, self) => self.indexOf(value) === index); const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); @@ -125087,8 +125204,7 @@ function getErrorSummaryText(errorCount, filesInError, newLine, host) { } function createTabularErrorsDisplay(filesInError, host) { const distinctFiles = filesInError.filter((value, index, self) => index === self.findIndex((file) => (file == null ? void 0 : file.fileName) === (value == null ? void 0 : value.fileName))); - if (distinctFiles.length === 0) - return ""; + if (distinctFiles.length === 0) return ""; const numberLength = (num) => Math.log(num) * Math.LOG10E + 1; const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]); const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0); @@ -125185,8 +125301,7 @@ function explainIfFileIsRedirectAndImpliedFormat(file, options, fileNameConverto function getMatchedFileSpec(program, fileName) { var _a; const configFile = program.getCompilerOptions().configFile; - if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) - return void 0; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) return void 0; const filePath = program.getCanonicalFileName(fileName); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); const index = findIndex(configFile.configFileSpecs.validatedFilesSpec, (fileSpec) => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); @@ -125195,16 +125310,13 @@ function getMatchedFileSpec(program, fileName) { function getMatchedIncludeSpec(program, fileName) { var _a, _b; const configFile = program.getCompilerOptions().configFile; - if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) - return void 0; - if (configFile.configFileSpecs.isDefaultIncludeSpec) - return true; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) return void 0; + if (configFile.configFileSpecs.isDefaultIncludeSpec) return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); const index = findIndex((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { - if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) - return false; + if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); @@ -125253,20 +125365,18 @@ function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { } switch (reason.kind) { case 0 /* RootFile */: - if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Root_file_specified_for_compilation - ); + if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Root_file_specified_for_compilation + ); const fileName = getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory()); const matchedByFiles = getMatchedFileSpec(program, fileName); - if (matchedByFiles) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Part_of_files_list_in_tsconfig_json - ); + if (matchedByFiles) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Part_of_files_list_in_tsconfig_json + ); const matchedByInclude = getMatchedIncludeSpec(program, fileName); return isString(matchedByInclude) ? chainDiagnosticMessages( /*details*/ @@ -125302,13 +125412,12 @@ function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { ); } case 6 /* LibFile */: { - if (reason.index !== void 0) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Library_0_specified_in_compilerOptions, - options.lib[reason.index] - ); + if (reason.index !== void 0) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Library_0_specified_in_compilerOptions, + options.lib[reason.index] + ); const target = getNameOfScriptTarget(getEmitScriptTarget(options)); const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library]; return chainDiagnosticMessages( @@ -125605,27 +125714,23 @@ function performIncrementalCompilation(input) { (s) => host.trace && host.trace(s), input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : void 0 ); - if (input.afterProgramEmitAndDiagnostics) - input.afterProgramEmitAndDiagnostics(builderProgram); + if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); return exitStatus; } // src/compiler/watchPublic.ts function readBuilderProgram(compilerOptions, host) { const buildInfoPath = getTsBuildInfoEmitOutputFilePath(compilerOptions); - if (!buildInfoPath) - return void 0; + if (!buildInfoPath) return void 0; let buildInfo; if (host.getBuildInfo) { buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); } else { const content = host.readFile(buildInfoPath); - if (!content) - return void 0; + if (!content) return void 0; buildInfo = getBuildInfo(buildInfoPath, content); } - if (!buildInfo || buildInfo.version !== version || !buildInfo.program) - return void 0; + if (!buildInfo || buildInfo.version !== version || !buildInfo.program) return void 0; return createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host); } function createIncrementalCompilerHost(options, system = sys) { @@ -125747,8 +125852,7 @@ function createWatchProgram(host) { builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); - if (configFileName) - updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); + if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; function close() { clearInvalidateResolutionsOfFailedLookupLocations(); @@ -125782,12 +125886,12 @@ function createWatchProgram(host) { var _a; (_a = config.watcher) == null ? void 0 : _a.close(); config.watcher = void 0; - if (config.watchedDirectories) - clearMap(config.watchedDirectories, closeFileWatcherOf); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); config.watchedDirectories = void 0; }); parsedConfigs = void 0; } + builderProgram = void 0; } function getResolutionCache() { return resolutionCache; @@ -125857,8 +125961,7 @@ function createWatchProgram(host) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); - if (projectReferences) - writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); + if (projectReferences) writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -125955,10 +126058,8 @@ function createWatchProgram(host) { } function getSourceVersion(path, readFileWithCache) { const hostSourceFile = sourceFilesCache.get(path); - if (!hostSourceFile) - return void 0; - if (hostSourceFile.version) - return hostSourceFile.version; + if (!hostSourceFile) return void 0; + if (hostSourceFile.version) return hostSourceFile.version; const text = readFileWithCache(path); return text !== void 0 ? getSourceFileVersionAsHashFromText(compilerHost, text) : void 0; } @@ -125987,8 +126088,7 @@ function createWatchProgram(host) { return resolutionCache.hasChangedAutomaticTypeDirectiveNames(); } function clearInvalidateResolutionsOfFailedLookupLocations() { - if (!timerToInvalidateFailedLookupResolutions) - return false; + if (!timerToInvalidateFailedLookupResolutions) return false; host.clearTimeout(timerToInvalidateFailedLookupResolutions); timerToInvalidateFailedLookupResolutions = void 0; return true; @@ -126097,8 +126197,7 @@ function createWatchProgram(host) { const configPath = toPath3(configFileName2); let config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); if (config) { - if (!config.updateLevel) - return config.parsedCommandLine; + if (!config.updateLevel) return config.parsedCommandLine; if (config.parsedCommandLine && config.updateLevel === 1 /* RootNamesAndUpdate */ && !host.getParsedCommandLine) { writeLog("Reloading new file names and options"); Debug.assert(compilerOptions); @@ -126142,11 +126241,9 @@ function createWatchProgram(host) { var _a; const path = toPath3(fileName); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(path); - if (!config) - return; + if (!config) return; parsedConfigs.delete(path); - if (config.watchedDirectories) - clearMap(config.watchedDirectories, closeFileWatcherOf); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); (_a = config.watcher) == null ? void 0 : _a.close(); clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); } @@ -126215,8 +126312,7 @@ function createWatchProgram(host) { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 - })) - return; + })) return; if (updateLevel !== 2 /* Full */) { updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); @@ -126237,18 +126333,15 @@ function createWatchProgram(host) { (_fileName, eventKind) => { var _a; updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); - if (extendedConfigCache) - cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); + if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); const projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a.projects; - if (!(projects == null ? void 0 : projects.size)) - return; + if (!(projects == null ? void 0 : projects.size)) return; projects.forEach((projectPath) => { if (configFileName && toPath3(configFileName) === projectPath) { updateLevel = 2 /* Full */; } else { const config = parsedConfigs == null ? void 0 : parsedConfigs.get(projectPath); - if (config) - config.updateLevel = 2 /* Full */; + if (config) config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); } scheduleProgramUpdate(); @@ -126268,8 +126361,7 @@ function createWatchProgram(host) { (_fileName, eventKind) => { updateCachedSystemWithFile(configFileName2, configPath, eventKind); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (config) - config.updateLevel = 2 /* Full */; + if (config) config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); scheduleProgramUpdate(); }, @@ -126291,8 +126383,7 @@ function createWatchProgram(host) { } nextSourceFileVersion(fileOrDirectoryPath); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (!(config == null ? void 0 : config.parsedCommandLine)) - return; + if (!(config == null ? void 0 : config.parsedCommandLine)) return; if (isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath3(directory), fileOrDirectory, @@ -126304,8 +126395,7 @@ function createWatchProgram(host) { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 - })) - return; + })) return; if (config.updateLevel !== 2 /* Full */) { config.updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); @@ -126389,8 +126479,7 @@ function createSolutionBuilderWithWatchHost(system = sys, createProgram2, report function getCompilerOptionsOfBuildOptions(buildOptions) { const result = {}; commonOptionsWithBuild.forEach((option) => { - if (hasProperty(buildOptions, option.name)) - result[option.name] = buildOptions[option.name]; + if (hasProperty(buildOptions, option.name)) result[option.name] = buildOptions[option.name]; }); return result; } @@ -126541,8 +126630,7 @@ function toPath2(state, fileName) { function toResolvedConfigFilePath(state, fileName) { const { resolvedConfigFilePaths } = state; const path = resolvedConfigFilePaths.get(fileName); - if (path !== void 0) - return path; + if (path !== void 0) return path; const resolvedPath = toPath2(state, fileName); resolvedConfigFilePaths.set(fileName, resolvedPath); return resolvedPath; @@ -126566,8 +126654,7 @@ function parseConfigFile(state, configFileName, configFilePath) { let parsed; if (host.getParsedCommandLine) { parsed = host.getParsedCommandLine(configFileName); - if (!parsed) - diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName); + if (!parsed) diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName); } else { parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = (d) => diagnostic = d; parsed = getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions); @@ -126593,8 +126680,7 @@ function createBuildOrder(state, roots) { return circularDiagnostics ? { buildOrder: buildOrder || emptyArray, circularDiagnostics } : buildOrder || emptyArray; function visit(configFileName, inCircularContext) { const projPath = toResolvedConfigFilePath(state, configFileName); - if (permanentMarks.has(projPath)) - return; + if (permanentMarks.has(projPath)) return; if (temporaryMarks.has(projPath)) { if (!inCircularContext) { (circularDiagnostics || (circularDiagnostics = [])).push( @@ -126676,16 +126762,14 @@ function createStateBuildOrder(state) { function getBuildOrderFor(state, project, onlyReferences) { const resolvedProject = project && resolveProjectName(state, project); const buildOrderFromState = getBuildOrder(state); - if (isCircularBuildOrder(buildOrderFromState)) - return buildOrderFromState; + if (isCircularBuildOrder(buildOrderFromState)) return buildOrderFromState; if (resolvedProject) { const projectPath = toResolvedConfigFilePath(state, resolvedProject); const projectIndex = findIndex( buildOrderFromState, (configFileName) => toResolvedConfigFilePath(state, configFileName) === projectPath ); - if (projectIndex === -1) - return void 0; + if (projectIndex === -1) return void 0; } const buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState; Debug.assert(!isCircularBuildOrder(buildOrder)); @@ -126726,8 +126810,7 @@ function enableCache(state) { }; } function disableCache(state) { - if (!state.cache) - return; + if (!state.cache) return; const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; @@ -126755,11 +126838,9 @@ function addProjToQueue({ projectPendingBuild }, proj, updateLevel) { } } function setupInitialBuild(state, cancellationToken) { - if (!state.allProjectBuildPending) - return; + if (!state.allProjectBuildPending) return; state.allProjectBuildPending = false; - if (state.options.watch) - reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); + if (state.options.watch) reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); enableCache(state); const buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state)); buildOrder.forEach( @@ -126853,8 +126934,7 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec if (step === 4 /* EmitBuildInfo */) { return emitBuildInfo(writeFile2, cancellationToken); } - if (step !== 3 /* Emit */) - return void 0; + if (step !== 3 /* Emit */) return void 0; return emit(writeFile2, cancellationToken, customTransformers); }, done @@ -126880,8 +126960,7 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec step = 5 /* QueueReferencingProjects */; return; } - if (state.options.verbose) - reportStatus(state, Diagnostics.Building_project_0, project); + if (state.options.verbose) reportStatus(state, Diagnostics.Building_project_0, project); if (config.fileNames.length === 0) { reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); buildResult = 0 /* None */; @@ -127004,12 +127083,10 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => { const path = toPath2(state, name); emittedOutputs.set(toPath2(state, name), name); - if (data == null ? void 0 : data.buildInfo) - setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); + if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0; writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (data == null ? void 0 : data.differsOnlyInMap) - state.host.setModifiedTime(name, modifiedTime); + if (data == null ? void 0 : data.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime); else if (!isIncremental && state.watch) { (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } @@ -127026,12 +127103,9 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec Debug.assertIsDefined(program); Debug.assert(step === 4 /* EmitBuildInfo */); const emitResult = program.emitBuildInfo((name, text, writeByteOrderMark, onError, sourceFiles, data) => { - if (data == null ? void 0 : data.buildInfo) - setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */); - if (writeFileCallback) - writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); - else - state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */); + if (writeFileCallback) writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); @@ -127105,17 +127179,14 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec } } function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { - if (!state.projectPendingBuild.size) - return void 0; - if (isCircularBuildOrder(buildOrder)) - return void 0; + if (!state.projectPendingBuild.size) return void 0; + if (isCircularBuildOrder(buildOrder)) return void 0; const { options, projectPendingBuild } = state; for (let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { const project = buildOrder[projectIndex]; const projectPath = toResolvedConfigFilePath(state, project); const updateLevel = state.projectPendingBuild.get(projectPath); - if (updateLevel === void 0) - continue; + if (updateLevel === void 0) continue; if (reportQueue) { reportQueue = false; reportBuildQueue(state, buildOrder); @@ -127211,8 +127282,7 @@ function createInvalidatedProjectWithInfo(state, info, buildOrder) { } function getNextInvalidatedProject(state, buildOrder, reportQueue) { const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); - if (!info) - return info; + if (!info) return info; return createInvalidatedProjectWithInfo(state, info, buildOrder); } function listEmittedFile({ write }, proj, file) { @@ -127221,17 +127291,14 @@ function listEmittedFile({ write }, proj, file) { } } function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) { - if (options.force) - return void 0; + if (options.force) return void 0; const value = builderPrograms.get(proj); - if (value) - return value; + if (value) return value; return readBuilderProgram(parsed.options, compilerHost); } function afterProgramDone(state, program) { if (program) { - if (state.write) - listFiles(program, state.write); + if (state.write) listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); } @@ -127243,8 +127310,7 @@ function buildErrors(state, resolvedPath, program, config, diagnostics, buildRes const canEmitBuildInfo = program && !program.getCompilerOptions().outFile; reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: 0 /* Unbuildable */, reason: `${errorType} errors` }); - if (canEmitBuildInfo) - return { buildResult, step: 4 /* EmitBuildInfo */ }; + if (canEmitBuildInfo) return { buildResult, step: 4 /* EmitBuildInfo */ }; afterProgramDone(state, program); return { buildResult, step: 5 /* QueueReferencingProjects */ }; } @@ -127255,17 +127321,13 @@ function getModifiedTime2(state, fileName) { const path = toPath2(state, fileName); const existing = state.filesWatched.get(path); if (state.watch && !!existing) { - if (!isFileWatcherWithModifiedTime(existing)) - return existing; - if (existing.modifiedTime) - return existing.modifiedTime; + if (!isFileWatcherWithModifiedTime(existing)) return existing; + if (existing.modifiedTime) return existing.modifiedTime; } const result = getModifiedTime(state.host, fileName); if (state.watch) { - if (existing) - existing.modifiedTime = result; - else - state.filesWatched.set(path, result); + if (existing) existing.modifiedTime = result; + else state.filesWatched.set(path, result); } return result; } @@ -127304,11 +127366,9 @@ function watchFile(state, file, callback, pollingInterval, options, watchType, p }; } function getOutputTimeStampMap(state, resolvedConfigFilePath) { - if (!state.watch) - return void 0; + if (!state.watch) return void 0; let result = state.outputTimeStamps.get(resolvedConfigFilePath); - if (!result) - state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); + if (!result) state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); return result; } function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { @@ -127318,8 +127378,7 @@ function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags if (existing) { existing.buildInfo = buildInfo; existing.modifiedTime = modifiedTime; - if (!(resultFlags & 2 /* DeclarationOutputUnchanged */)) - existing.latestChangedDtsTime = modifiedTime; + if (!(resultFlags & 2 /* DeclarationOutputUnchanged */)) existing.latestChangedDtsTime = modifiedTime; } else { state.buildInfoCache.set(resolvedConfigPath, { path: toPath2(state, buildInfoPath), @@ -127356,7 +127415,7 @@ function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var _a, _b, _c; + var _a, _b, _c, _d; if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) { return { type: 15 /* ContainerOnly */ @@ -127387,12 +127446,10 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { upstreamProjectName: ref.path }; } - if (!force) - (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); + if (!force) (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); } } - if (force) - return { type: 16 /* ForceBuild */ }; + if (force) return { type: 16 /* ForceBuild */ }; const { host } = state; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); let oldestOutputFileName; @@ -127430,7 +127487,7 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { }; } if (buildInfo.program) { - if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? ((_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length) || ((_c = buildInfo.program.emitDiagnosticsPerFile) == null ? void 0 : _c.length) : some(buildInfo.program.semanticDiagnosticsPerFile, isArray))) { + if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? ((_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length) || ((_c = buildInfo.program.emitDiagnosticsPerFile) == null ? void 0 : _c.length) : (_d = buildInfo.program.semanticDiagnosticsPerFile) == null ? void 0 : _d.length)) { return { type: 7 /* OutOfDateBuildInfo */, buildInfoFile: buildInfoPath @@ -127459,17 +127516,17 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { reason: `${inputFile} does not exist` }; } + const inputPath = buildInfoProgram ? toPath2(state, inputFile) : void 0; if (buildInfoTime && buildInfoTime < inputTime) { let version2; let currentVersion; if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); - version2 = buildInfoVersionMap.fileInfos.get(toPath2(state, inputFile)); - const text = version2 ? state.readFileWithCache(inputFile) : void 0; + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + const resolvedInputPath = buildInfoVersionMap.roots.get(inputPath); + version2 = buildInfoVersionMap.fileInfos.get(resolvedInputPath ?? inputPath); + const text = version2 ? state.readFileWithCache(resolvedInputPath ?? inputFile) : void 0; currentVersion = text !== void 0 ? getSourceFileVersionAsHashFromText(host, text) : void 0; - if (version2 && version2 === currentVersion) - pseudoInputUpToDate = true; + if (version2 && version2 === currentVersion) pseudoInputUpToDate = true; } if (!version2 || version2 !== currentVersion) { return { @@ -127483,20 +127540,21 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { newestInputFileName = inputFile; newestInputFileTime = inputTime; } - if (buildInfoProgram) - seenRoots.add(toPath2(state, inputFile)); + if (buildInfoProgram) seenRoots.add(inputPath); } if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); - for (const existingRoot of buildInfoVersionMap.roots) { - if (!seenRoots.has(existingRoot)) { - return { - type: 9 /* OutOfDateRoots */, - buildInfoFile: buildInfoPath, - inputFile: existingRoot - }; - } + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + const existingRoot = forEachEntry( + buildInfoVersionMap.roots, + // File was root file when project was built but its not any more + (_resolved, existingRoot2) => !seenRoots.has(existingRoot2) ? existingRoot2 : void 0 + ); + if (existingRoot) { + return { + type: 9 /* OutOfDateRoots */, + buildInfoFile: buildInfoPath, + inputFile: existingRoot + }; } } if (!buildInfoPath) { @@ -127556,18 +127614,15 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { } } const configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; + if (configStatus) return configStatus; const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, (configFile) => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName)); - if (extendedConfigStatus) - return extendedConfigStatus; + if (extendedConfigStatus) return extendedConfigStatus; const packageJsonLookups = state.lastCachedPackageJsonLookups.get(resolvedPath); const dependentPackageFileStatus = packageJsonLookups && forEachKey( packageJsonLookups, (path) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName) ); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; + if (dependentPackageFileStatus) return dependentPackageFileStatus; return { type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 14 /* UpToDateWithInputFileText */ : 1 /* UpToDate */, newestInputFileTime, @@ -127595,14 +127650,12 @@ function getUpToDateStatus(state, project, resolvedPath) { return actual; } function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { - if (proj.options.noEmit) - return; + if (proj.options.noEmit) return; let now; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(proj.options); if (buildInfoPath) { if (!(skipOutputs == null ? void 0 : skipOutputs.has(toPath2(state, buildInfoPath)))) { - if (!!state.options.verbose) - reportStatus(state, verboseMessage, proj.options.configFilePath); + if (!!state.options.verbose) reportStatus(state, verboseMessage, proj.options.configFilePath); state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; } @@ -127617,8 +127670,7 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, let reportVerbose = !!state.options.verbose; for (const file of outputs) { const path = toPath2(state, file); - if (skipOutputs == null ? void 0 : skipOutputs.has(path)) - continue; + if (skipOutputs == null ? void 0 : skipOutputs.has(path)) continue; if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); @@ -127631,16 +127683,13 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, } } outputTimeStampMap == null ? void 0 : outputTimeStampMap.forEach((_value, key) => { - if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) - outputTimeStampMap.delete(key); + if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) outputTimeStampMap.delete(key); }); } function getLatestChangedDtsTime(state, options, resolvedConfigPath) { - if (!options.composite) - return void 0; + if (!options.composite) return void 0; const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); - if (entry.latestChangedDtsTime !== void 0) - return entry.latestChangedDtsTime || void 0; + if (entry.latestChangedDtsTime !== void 0) return entry.latestChangedDtsTime || void 0; const latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0; entry.latestChangedDtsTime = latestChangedDtsTime || false; return latestChangedDtsTime; @@ -127656,22 +127705,17 @@ function updateOutputTimestamps(state, proj, resolvedPath) { }); } function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) { - if (buildResult & 124 /* AnyErrors */) - return; - if (!config.options.composite) - return; + if (buildResult & 124 /* AnyErrors */) return; + if (!config.options.composite) return; for (let index = projectIndex + 1; index < buildOrder.length; index++) { const nextProject = buildOrder[index]; const nextProjectPath = toResolvedConfigFilePath(state, nextProject); - if (state.projectPendingBuild.has(nextProjectPath)) - continue; + if (state.projectPendingBuild.has(nextProjectPath)) continue; const nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath); - if (!nextProjectConfig || !nextProjectConfig.projectReferences) - continue; + if (!nextProjectConfig || !nextProjectConfig.projectReferences) continue; for (const ref of nextProjectConfig.projectReferences) { const resolvedRefPath = resolveProjectName(state, ref.path); - if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) - continue; + if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) continue; const status = state.projectStatus.get(nextProjectPath); if (status) { switch (status.type) { @@ -127711,19 +127755,16 @@ function build(state, project, cancellationToken, writeFile2, getCustomTransform } function buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) { const buildOrder = getBuildOrderFor(state, project, onlyReferences); - if (!buildOrder) - return 3 /* InvalidProject_OutputsSkipped */; + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; setupInitialBuild(state, cancellationToken); let reportQueue = true; let successfulProjects = 0; while (true) { const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); - if (!invalidatedProject) - break; + if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken, writeFile2, getCustomTransformers == null ? void 0 : getCustomTransformers(invalidatedProject.project)); - if (!state.diagnostics.has(invalidatedProject.projectPath)) - successfulProjects++; + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } disableCache(state); reportErrorSummary(state, buildOrder); @@ -127739,8 +127780,7 @@ function clean(state, project, onlyReferences) { } function cleanWorker(state, project, onlyReferences) { const buildOrder = getBuildOrderFor(state, project, onlyReferences); - if (!buildOrder) - return 3 /* InvalidProject_OutputsSkipped */; + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); return 4 /* ProjectReferenceCycle_OutputsSkipped */; @@ -127755,12 +127795,10 @@ function cleanWorker(state, project, onlyReferences) { continue; } const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); - if (!outputs.length) - continue; + if (!outputs.length) continue; const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f))); for (const output of outputs) { - if (inputFileNames.has(toPath2(state, output))) - continue; + if (inputFileNames.has(toPath2(state, output))) continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -127815,8 +127853,7 @@ function buildNextInvalidatedProject(_timeoutType, state, changeDetected) { const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected); mark("SolutionBuilder::afterBuild"); measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); - if (buildOrder) - reportErrorSummary(state, buildOrder); + if (buildOrder) reportErrorSummary(state, buildOrder); } function buildNextInvalidatedProjectWorker(state, changeDetected) { state.timerToBuildInvalidatedProject = void 0; @@ -127837,16 +127874,14 @@ function buildNextInvalidatedProjectWorker(state, changeDetected) { invalidatedProject.done(); projectsBuilt++; while (state.projectPendingBuild.size) { - if (state.timerToBuildInvalidatedProject) - return; + if (state.timerToBuildInvalidatedProject) return; const info = getNextInvalidatedProjectCreateInfo( state, buildOrder, /*reportQueue*/ false ); - if (!info) - break; + if (!info) break; if (info.kind !== 1 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) { scheduleBuildInvalidatedProject( state, @@ -127858,16 +127893,14 @@ function buildNextInvalidatedProjectWorker(state, changeDetected) { } const project = createInvalidatedProjectWithInfo(state, info, buildOrder); project.done(); - if (info.kind !== 1 /* UpdateOutputFileStamps */) - projectsBuilt++; + if (info.kind !== 1 /* UpdateOutputFileStamps */) projectsBuilt++; } } disableCache(state); return buildOrder; } function watchConfigFile(state, resolved, resolvedPath, parsed) { - if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) - return; + if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; state.allWatchedConfigFiles.set( resolvedPath, watchFile( @@ -127901,8 +127934,7 @@ function watchExtendedConfigFiles(state, resolvedPath, parsed) { ); } function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; + if (!state.watch) return; updateWatchingWildcardDirectories( getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), parsed.wildcardDirectories, @@ -127921,8 +127953,7 @@ function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, writeLog: (s) => state.writeLog(s), toPath: (fileName) => toPath2(state, fileName) - })) - return; + })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); }, flags, @@ -127933,8 +127964,7 @@ function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { ); } function watchInputFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; + if (!state.watch) return; mutateMap( getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), new Set(parsed.fileNames), @@ -127953,8 +127983,7 @@ function watchInputFiles(state, resolved, resolvedPath, parsed) { ); } function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch || !state.lastCachedPackageJsonLookups) - return; + if (!state.watch || !state.lastCachedPackageJsonLookups) return; mutateMap( getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), state.lastCachedPackageJsonLookups.get(resolvedPath), @@ -127973,8 +128002,7 @@ function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { ); } function startWatching(state, buildOrder) { - if (!state.watchAllProjectsPending) - return; + if (!state.watchAllProjectsPending) return; mark("SolutionBuilder::beforeWatcherCreation"); state.watchAllProjectsPending = false; for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) { @@ -128061,8 +128089,7 @@ function reportParseConfigFileDiagnostic(state, proj) { reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]); } function reportErrorSummary(state, buildOrder) { - if (!state.needsSummary) - return; + if (!state.needsSummary) return; state.needsSummary = false; const canReportSummary = state.watch || !!state.host.reportErrorSummary; const { diagnostics } = state; @@ -128071,10 +128098,8 @@ function reportErrorSummary(state, buildOrder) { if (isCircularBuildOrder(buildOrder)) { reportBuildQueue(state, buildOrder.buildOrder); reportErrors(state, buildOrder.circularDiagnostics); - if (canReportSummary) - totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics); - if (canReportSummary) - filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)]; + if (canReportSummary) totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics); + if (canReportSummary) filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)]; } else { buildOrder.forEach((project) => { const projectPath = toResolvedConfigFilePath(state, project); @@ -128082,10 +128107,8 @@ function reportErrorSummary(state, buildOrder) { reportErrors(state, diagnostics.get(projectPath) || emptyArray); } }); - if (canReportSummary) - diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors)); - if (canReportSummary) - diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors)); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]); } if (state.watch) { reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); @@ -128387,8 +128410,7 @@ function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) text.push(`${valueCandidates.valueType} ${valueCandidates.possibleValues}`); } if (defaultValueDescription) { - if (valueCandidates) - text.push(sys2.newLine); + if (valueCandidates) text.push(sys2.newLine); const diagType = getDiagnosticText(Diagnostics.default_Colon); text.push(`${diagType} ${defaultValueDescription}`); } @@ -128404,8 +128426,7 @@ function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) const ignoreValues = ["string"]; const ignoredDescriptions = [void 0, "false", "n/a"]; const defaultValueDescription2 = option2.defaultValueDescription; - if (option2.category === Diagnostics.Command_line_Options) - return false; + if (option2.category === Diagnostics.Command_line_Options) return false; if (contains(ignoreValues, valueCandidates2 == null ? void 0 : valueCandidates2.possibleValues) && contains(ignoredDescriptions, defaultValueDescription2)) { return false; } @@ -128741,8 +128762,7 @@ function executeCommandLineWorker(sys2, cb, commandLine) { configParseResult.options ); if (isWatchSet(configParseResult.options)) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; return createWatchOfConfigFile( sys2, cb, @@ -128778,8 +128798,7 @@ function executeCommandLineWorker(sys2, cb, commandLine) { commandLineOptions ); if (isWatchSet(commandLineOptions)) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; return createWatchOfFilesAndCompilerOptions( sys2, cb, @@ -128883,8 +128902,7 @@ function performBuild(sys2, cb, buildOptions, watchOptions, projects, errors) { return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); } if (buildOptions.watch) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; const buildHost2 = createSolutionBuilderWithWatchHost( sys2, /*createProgram*/ @@ -129089,10 +129107,8 @@ function createSolutionPerfomrance() { function addAggregateStatistic(s) { const existing = statistics == null ? void 0 : statistics.get(s.name); if (existing) { - if (existing.type === 2 /* memory */) - existing.value = Math.max(existing.value, s.value); - else - existing.value += s.value; + if (existing.type === 2 /* memory */) existing.value = Math.max(existing.value, s.value); + else existing.value += s.value; } else { (statistics ?? (statistics = /* @__PURE__ */ new Map())).set(s.name, s); } @@ -129105,8 +129121,7 @@ function createSolutionPerfomrance() { } } function reportSolutionBuilderTimes(builder, solutionPerformance) { - if (!solutionPerformance) - return; + if (!solutionPerformance) return; if (!isEnabled()) { sys.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n"); return; @@ -129123,8 +129138,7 @@ function reportSolutionBuilderTimes(builder, solutionPerformance) { statistics.push(s); }); forEachMeasure((name, duration) => { - if (isSolutionMarkOrMeasure(name)) - statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ }); + if (isSolutionMarkOrMeasure(name)) statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ }); }); disable(); enable(); @@ -129200,13 +129214,12 @@ function reportStatistics(sys2, program, solutionPerformance) { reportCountStatistic("Strict subtype cache size", caches.strictSubtype); if (isPerformanceEnabled) { forEachMeasure((name, duration) => { - if (!isSolutionMarkOrMeasure(name)) - reportTimeStatistic( - `${name} time`, - duration, - /*aggregate*/ - true - ); + if (!isSolutionMarkOrMeasure(name)) reportTimeStatistic( + `${name} time`, + duration, + /*aggregate*/ + true + ); }); } } else if (isPerformanceEnabled) { @@ -129261,12 +129274,10 @@ function reportStatistics(sys2, program, solutionPerformance) { } else { if (solutionPerformance) { forEachMeasure((name) => { - if (!isSolutionMarkOrMeasure(name)) - clearMeasures(name); + if (!isSolutionMarkOrMeasure(name)) clearMeasures(name); }); forEachMark((name) => { - if (!isSolutionMarkOrMeasure(name)) - clearMarks(name); + if (!isSolutionMarkOrMeasure(name)) clearMarks(name); }); } else { disable(); @@ -129275,8 +129286,7 @@ function reportStatistics(sys2, program, solutionPerformance) { } function reportStatisticalValue(s, aggregate) { statistics.push(s); - if (aggregate) - solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s); + if (aggregate) solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s); } function reportCountStatistic(name, count) { reportStatisticalValue( @@ -129343,8 +129353,8 @@ function createSyntacticTypeNodeBuilder(options, resolver) { serializeReturnTypeForSignature, serializeTypeOfExpression }; - function serializeExistingTypeAnnotation(type) { - return type === void 0 ? void 0 : !type.parent || !isParameter(type.parent) || !resolver.requiresAddingImplicitUndefined(type.parent) || canAddUndefined(type); + function serializeExistingTypeAnnotation(type, addUndefined) { + return type !== void 0 && (!addUndefined || type && canAddUndefined(type)) ? true : void 0; } function serializeTypeOfExpression(expr, context, addUndefined, preserveLiterals) { return typeFromExpression( @@ -129465,12 +129475,17 @@ function createSyntacticTypeNodeBuilder(options, resolver) { const declaredType = getEffectiveTypeAnnotationNode(node); const addUndefined = resolver.requiresAddingImplicitUndefined(node); let resultType; - if (!addUndefined) { - if (declaredType) { - return serializeExistingTypeAnnotation(declaredType); - } + if (declaredType) { + resultType = serializeExistingTypeAnnotation(declaredType, addUndefined); + } else { if (node.initializer && isIdentifier(node.name)) { - resultType = typeFromExpression(node.initializer, context); + resultType = typeFromExpression( + node.initializer, + context, + /*isConstContext*/ + void 0, + addUndefined + ); } } return resultType ?? inferTypeOfDeclaration(node, context); @@ -129639,7 +129654,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { expression, /*includeBigInt*/ false - ) && !isEntityNameExpression(expression)) { + )) { context.tracker.reportInferenceFallback(prop.name); result = false; } @@ -129648,27 +129663,11 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return result; } function typeFromObjectLiteral(objectLiteral, context, isConstContext) { - if (!canGetTypeFromObjectLiteral(objectLiteral, context)) - return false; + if (!canGetTypeFromObjectLiteral(objectLiteral, context)) return false; let canInferObjectLiteral = true; for (const prop of objectLiteral.properties) { Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop)); const name = prop.name; - if (prop.name.kind === 167 /* ComputedPropertyName */) { - if (!resolver.isNonNarrowedBindableName(prop.name)) { - context.tracker.reportInferenceFallback(prop.name); - } else if (isEntityNameExpression(prop.name.expression)) { - const visibilityResult = resolver.isEntityNameVisible( - prop.name.expression, - context.enclosingDeclaration, - /*shouldComputeAliasToMakeVisible*/ - false - ); - if (visibilityResult.accessibility !== 0 /* Accessible */) { - context.tracker.reportInferenceFallback(prop.name); - } - } - } switch (prop.kind) { case 174 /* MethodDeclaration */: canInferObjectLiteral = !!typeFromObjectLiteralMethod(prop, name, context) && canInferObjectLiteral; @@ -129723,8 +129722,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return true; } function canAddUndefined(node) { - if (!strictNullChecks) - return true; + if (!strictNullChecks) return true; if (isKeyword(node.kind) || node.kind === 201 /* LiteralType */ || node.kind === 184 /* FunctionType */ || node.kind === 185 /* ConstructorType */ || node.kind === 188 /* ArrayType */ || node.kind === 189 /* TupleType */ || node.kind === 187 /* TypeLiteral */ || node.kind === 203 /* TemplateLiteralType */ || node.kind === 197 /* ThisType */) { return true; } @@ -129750,6 +129748,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { function typeFromSingleReturnExpression(declaration, context) { let candidateExpr; if (declaration && !nodeIsMissing(declaration.body)) { + if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; const body = declaration.body; if (body && isBlock(body)) { forEachReturnStatement(body, (s) => { diff --git a/lib/tsserver.js b/lib/tsserver.js index 50cc6659cecd9..398a3a1edac70 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -85,8 +85,7 @@ function parseLoggingEnvironmentString(logEnvStr) { pathStart += " "; pathStart += args[i]; extraPartCounter++; - if (pathStart.charCodeAt(pathStart.length - 1) === typescript_exports.CharacterCodes.doubleQuote) - break; + if (pathStart.charCodeAt(pathStart.length - 1) === typescript_exports.CharacterCodes.doubleQuote) break; } } return { value: (0, typescript_exports.stripQuotes)(pathStart), extraPartCounter }; @@ -94,8 +93,7 @@ function parseLoggingEnvironmentString(logEnvStr) { } function parseServerMode() { const mode = typescript_exports.server.findArgument("--serverMode"); - if (!mode) - return void 0; + if (!mode) return void 0; switch (mode.toLowerCase()) { case "semantic": return typescript_exports.LanguageServiceMode.Semantic; @@ -173,8 +171,7 @@ function initializeNodeSystem() { (_c = typescript_exports.perfLogger) == null ? void 0 : _c.logErrEvent(s); break; } - if (!this.canWrite()) - return; + if (!this.canWrite()) return; s = `[${typescript_exports.server.nowString()}] ${s} `; if (!this.inGroup || this.firstInGroup) { @@ -295,10 +292,8 @@ function initializeNodeSystem() { let serverMode; let unknownServerMode; if (modeOrUnknown !== void 0) { - if (typeof modeOrUnknown === "number") - serverMode = modeOrUnknown; - else - unknownServerMode = modeOrUnknown; + if (typeof modeOrUnknown === "number") serverMode = modeOrUnknown; + else unknownServerMode = modeOrUnknown; } return { args: process.argv, diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index f4c59a84472d4..e6dfbf9200437 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -20,10 +20,18 @@ declare namespace ts { export import ClassificationType = ts.ClassificationType; export import CompletionsTriggerCharacter = ts.CompletionsTriggerCharacter; export import CompletionTriggerKind = ts.CompletionTriggerKind; + export import InlayHintKind = ts.InlayHintKind; export import OrganizeImportsMode = ts.OrganizeImportsMode; + export import RefactorActionInfo = ts.RefactorActionInfo; export import RefactorTriggerReason = ts.RefactorTriggerReason; export import RenameInfoFailure = ts.RenameInfoFailure; export import SemicolonPreference = ts.SemicolonPreference; + export import SignatureHelpCharacterTypedReason = ts.SignatureHelpCharacterTypedReason; + export import SignatureHelpInvokedReason = ts.SignatureHelpInvokedReason; + export import SignatureHelpParameter = ts.SignatureHelpParameter; + export import SignatureHelpRetriggerCharacter = ts.SignatureHelpRetriggerCharacter; + export import SignatureHelpRetriggeredReason = ts.SignatureHelpRetriggeredReason; + export import SignatureHelpTriggerCharacter = ts.SignatureHelpTriggerCharacter; export import SignatureHelpTriggerReason = ts.SignatureHelpTriggerReason; export import SymbolDisplayPart = ts.SymbolDisplayPart; export import UserPreferences = ts.UserPreferences; @@ -99,6 +107,7 @@ declare namespace ts { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", + GetPasteEdits = "getPasteEdits", OrganizeImports = "organizeImports", GetEditsForFileRename = "getEditsForFileRename", ConfigurePlugin = "configurePlugin", @@ -112,6 +121,7 @@ declare namespace ts { ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", ProvideInlayHints = "provideInlayHints", WatchChange = "watchChange", + MapCode = "mapCode", } /** * A TypeScript Server message @@ -469,6 +479,33 @@ declare namespace ts { files: string[]; }; } + /** + * Request refactorings at a given position post pasting text from some other location. + */ + export interface GetPasteEditsRequest extends Request { + command: CommandTypes.GetPasteEdits; + arguments: GetPasteEditsRequestArgs; + } + export interface GetPasteEditsRequestArgs extends FileRequestArgs { + /** The text that gets pasted in a file. */ + pastedText: string[]; + /** Locations of where the `pastedText` gets added in a file. If the length of the `pastedText` and `pastedLocations` are not the same, + * then the `pastedText` is combined into one and added at all the `pastedLocations`. + */ + pasteLocations: TextSpan[]; + /** The source location of each `pastedText`. If present, the length of `spans` must be equal to the length of `pastedText`. */ + copiedFrom?: { + file: string; + spans: TextSpan[]; + }; + } + export interface GetPasteEditsResponse extends Response { + body: PasteEditsAction; + } + export interface PasteEditsAction { + edits: FileCodeEdits[]; + fixId?: {}; + } export interface GetEditsForRefactorRequest extends Request { command: CommandTypes.GetEditsForRefactor; arguments: GetEditsForRefactorRequestArgs; @@ -1733,6 +1770,33 @@ declare namespace ts { export interface InlayHintsResponse extends Response { body?: InlayHintItem[]; } + export interface MapCodeRequestArgs extends FileRequestArgs { + /** + * The files and changes to try and apply/map. + */ + mapping: MapCodeRequestDocumentMapping; + } + export interface MapCodeRequestDocumentMapping { + /** + * The specific code to map/insert/replace in the file. + */ + contents: string[]; + /** + * Areas of "focus" to inform the code mapper with. For example, cursor + * location, current selection, viewport, etc. Nested arrays denote + * priority: toplevel arrays are more important than inner arrays, and + * inner array priorities are based on items within that array. Items + * earlier in the arrays have higher priority. + */ + focusLocations?: TextSpan[][]; + } + export interface MapCodeRequest extends FileRequest { + command: CommandTypes.MapCode; + arguments: MapCodeRequestArgs; + } + export interface MapCodeResponse extends Response { + body: readonly FileCodeEdits[]; + } /** * Synchronous request for semantic diagnostics of one file. */ @@ -2720,7 +2784,6 @@ declare namespace ts { private compilerOptions; compileOnSaveEnabled: boolean; protected watchOptions: WatchOptions | undefined; - private rootFiles; private rootFilesMap; private program; private externalFiles; @@ -2801,7 +2864,7 @@ declare namespace ts { private detachScriptInfoIfNotRoot; isClosed(): boolean; hasRoots(): boolean; - getRootFiles(): ts.server.NormalizedPath[]; + getRootFiles(): NormalizedPath[]; getRootScriptInfos(): ts.server.ScriptInfo[]; getScriptInfos(): ScriptInfo[]; getExcludedFiles(): readonly NormalizedPath[]; @@ -2872,8 +2935,6 @@ declare namespace ts { */ class ConfiguredProject extends Project { readonly canonicalConfigFilePath: NormalizedPath; - /** Ref count to the project when opened from external project */ - private externalProjectRefCount; private projectReferences; /** * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph @@ -3117,6 +3178,10 @@ declare namespace ts { * Open files: with value being project root path, and key being Path of the file that is open */ readonly openFiles: Map; + /** Config files looked up and cached config files for open script info */ + private readonly configFileForOpenFiles; + /** Set of open script infos that are root of inferred project */ + private rootOfInferredProjects; /** * Map of open files that are opened without complete path but have projectRoot as current directory */ @@ -3135,6 +3200,11 @@ declare namespace ts { private safelist; private readonly legacySafelist; private pendingProjectUpdates; + /** + * All the open script info that needs recalculation of the default project, + * this also caches config file info before config file change was detected to use it in case projects are not updated yet + */ + private pendingOpenFileProjectUpdates?; readonly currentDirectory: NormalizedPath; readonly toCanonicalFileName: (f: string) => string; readonly host: ServerHost; @@ -3166,6 +3236,11 @@ declare namespace ts { setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; + /** + * If there is default project calculation pending for this file, + * then it completes that calculation so that correct default project is used for the project + */ + private tryGetDefaultProjectForEnsuringConfiguredProjectForFile; private doEnsureDefaultProjectForFile; getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; /** @@ -3185,13 +3260,6 @@ declare namespace ts { private delayUpdateSourceInfoProjects; private delayUpdateProjectsOfScriptInfoPath; private handleDeletedFile; - /** - * This function goes through all the openFiles and tries to file the config file for them. - * If the config file is found and it refers to existing project, it schedules the reload it for reload - * If there is no existing project it just opens the configured project for the config file - * shouldReloadProjectFor provides a way to filter out files to reload configured project for - */ - private delayReloadConfiguredProjectsForFile; private removeProject; private assignOrphanScriptInfosToInferredProject; /** @@ -3201,14 +3269,6 @@ declare namespace ts { private closeOpenFile; private deleteScriptInfo; private configFileExists; - /** - * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project - */ - private configFileExistenceImpactsRootOfInferredProject; - /** - * This is called on file close, so that we stop watching the config file for this script info - */ - private stopWatchingConfigFilesForClosedScriptInfo; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -3218,17 +3278,10 @@ declare namespace ts { * the newly opened file. */ private forEachConfigFileLocation; - /** - * This function tries to search for a tsconfig.json for the given file. - * This is different from the method the compiler uses because - * the compiler can assume it will always start searching in the - * current directory (the directory in which tsc was invoked). - * The server must start searching from the directory containing - * the newly opened file. - * If script info is passed in, it is asserted to be open script info - * otherwise just file name - */ - private getConfigFileNameForFile; + /** Get cached configFileName for scriptInfo or ancestor of open script info */ + private getConfigFileNameForFileFromCache; + /** Caches the configFilename for script info or ancestor of open script info */ + private setConfigFileNameForFileInCache; private printProjects; private getConfiguredProjectByCanonicalConfigFilePath; private findExternalProjectByProjectName; @@ -3269,12 +3322,6 @@ declare namespace ts { * This does not reload contents of open files from disk. But we could do that if needed */ reloadProjects(): void; - /** - * This function goes through all the openFiles and tries to file the config file for them. - * If the config file is found and it refers to existing project, it reloads it either immediately - * If there is no existing project it just opens the configured project for the config file - */ - private reloadConfiguredProjectForFiles; /** * Remove the root of inferred project if script info is part of another project */ @@ -3296,11 +3343,21 @@ declare namespace ts { private findExternalProjectContainingOpenScriptInfo; private getOrCreateOpenScriptInfo; private assignProjectToOpenedScriptInfo; - private createAncestorProjects; + /** + * Finds the default configured project for given info + * For any tsconfig found, it looks into that project, if not then all its references, + * The search happens for all tsconfigs till projectRootPath + */ + private tryFindDefaultConfiguredProjectForOpenScriptInfo; + /** + * Finds the default configured project, if found, it creates the solution projects (does not load them right away) + * with Find: finds the projects even if the project is deferredClosed + */ + private tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo; private ensureProjectChildren; - private cleanupAfterOpeningFile; + private cleanupConfiguredProjects; + private cleanupProjectsAndScriptInfos; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; - private removeOrphanConfiguredProjects; private removeOrphanScriptInfos; private telemetryOnOpenFile; /** @@ -3309,7 +3366,6 @@ declare namespace ts { */ closeClientFile(uncheckedFileName: string): void; private collectChanges; - private closeConfiguredProjectReferencedFromExternalProject; closeExternalProject(uncheckedFileName: string): void; openExternalProjects(projects: protocol.ExternalProject[]): void; /** Makes a filename safe to insert in a RegExp */ @@ -3440,6 +3496,7 @@ declare namespace ts { private getLinkedEditingRange; private getDocumentHighlights; private provideInlayHints; + private mapCode; private setCompilerOptionsForInferredProjects; private getProjectInfo; private getProjectInfoWorker; @@ -3499,6 +3556,7 @@ declare namespace ts { private getApplicableRefactors; private getEditsForRefactor; private getMoveToRefactoringFileSuggestions; + private getPasteEdits; private organizeImports; private getEditsForFileRename; private getCodeFixes; @@ -3507,6 +3565,7 @@ declare namespace ts { private getStartAndEndPosition; private mapCodeAction; private mapCodeFixAction; + private mapPasteEditsAction; private mapTextChangesToCodeEdits; private mapTextChangeToCodeEdit; private convertTextChangeToCodeEdit; @@ -9456,6 +9515,7 @@ declare namespace ts { interface EmitOutput { outputFiles: OutputFile[]; emitSkipped: boolean; + diagnostics: readonly Diagnostic[]; } interface OutputFile { name: string; @@ -10102,6 +10162,7 @@ declare namespace ts { uncommentSelection(fileName: string, textRange: TextRange): TextChange[]; getSupportedCodeFixes(fileName?: string): readonly string[]; dispose(): void; + getPasteEdits(args: PasteEditsArgs, formatOptions: FormatCodeSettings): PasteEdits; } interface JsxClosingTagInfo { readonly newText: string; @@ -10119,6 +10180,20 @@ declare namespace ts { SortAndCombine = "SortAndCombine", RemoveUnused = "RemoveUnused", } + interface PasteEdits { + edits: readonly FileTextChanges[]; + fixId?: {}; + } + interface PasteEditsArgs { + targetFile: string; + pastedText: string[]; + pasteLocations: TextRange[]; + copiedFrom: { + file: string; + range: TextRange[]; + } | undefined; + preferences: UserPreferences; + } interface OrganizeImportsArgs extends CombinedCodeFixScope { /** @deprecated Use `mode` instead */ skipDestructiveCodeActions?: boolean; diff --git a/lib/typescript.js b/lib/typescript.js index 6b52dd6758621..e1e6b46315779 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -68,7 +68,6 @@ __export(typescript_exports, { EmitHint: () => EmitHint, EmitOnly: () => EmitOnly, EndOfLineState: () => EndOfLineState, - EnumKind: () => EnumKind, ExitStatus: () => ExitStatus, ExportKind: () => ExportKind, Extension: () => Extension, @@ -95,10 +94,11 @@ __export(typescript_exports, { IndexKind: () => IndexKind, InferenceFlags: () => InferenceFlags, InferencePriority: () => InferencePriority, - InlayHintKind: () => InlayHintKind, + InlayHintKind: () => InlayHintKind2, InlayHints: () => ts_InlayHints_exports, InternalEmitFlags: () => InternalEmitFlags, InternalSymbolName: () => InternalSymbolName, + IntersectionFlags: () => IntersectionFlags, InvalidatedProjectKind: () => InvalidatedProjectKind, JSDocParsingMode: () => JSDocParsingMode, JsDoc: () => ts_JsDoc_exports, @@ -112,6 +112,7 @@ __export(typescript_exports, { LexicalEnvironmentFlags: () => LexicalEnvironmentFlags, ListFormat: () => ListFormat, LogLevel: () => LogLevel, + MapCode: () => ts_MapCode_exports, MemberOverrideStatus: () => MemberOverrideStatus, ModifierFlags: () => ModifierFlags, ModuleDetectionKind: () => ModuleDetectionKind, @@ -259,6 +260,7 @@ __export(typescript_exports, { canHaveModifiers: () => canHaveModifiers, canHaveModuleSpecifier: () => canHaveModuleSpecifier, canHaveSymbol: () => canHaveSymbol, + canIncludeBindAndCheckDiagnsotics: () => canIncludeBindAndCheckDiagnsotics, canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, canProduceDiagnostics: () => canProduceDiagnostics, canUsePropertyAccess: () => canUsePropertyAccess, @@ -302,6 +304,7 @@ __export(typescript_exports, { collectExternalModuleInfo: () => collectExternalModuleInfo, combine: () => combine, combinePaths: () => combinePaths, + commandLineOptionOfCustomType: () => commandLineOptionOfCustomType, commentPragmas: () => commentPragmas, commonOptionsWithBuild: () => commonOptionsWithBuild, commonPackageFolders: () => commonPackageFolders, @@ -511,6 +514,7 @@ __export(typescript_exports, { defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, diagnosticCategoryName: () => diagnosticCategoryName, diagnosticToString: () => diagnosticToString, + diagnosticsEqualityComparer: () => diagnosticsEqualityComparer, directoryProbablyExists: () => directoryProbablyExists, directorySeparator: () => directorySeparator, displayPart: () => displayPart, @@ -530,6 +534,7 @@ __export(typescript_exports, { emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments, emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition, + emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking, emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, emptyArray: () => emptyArray, emptyFileSystemEntries: () => emptyFileSystemEntries, @@ -629,6 +634,7 @@ __export(typescript_exports, { forEachKey: () => forEachKey, forEachLeadingCommentRange: () => forEachLeadingCommentRange, forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft, + forEachNameOfDefaultExport: () => forEachNameOfDefaultExport, forEachPropertyAssignment: () => forEachPropertyAssignment, forEachResolvedProjectReference: () => forEachResolvedProjectReference, forEachReturnStatement: () => forEachReturnStatement, @@ -684,6 +690,7 @@ __export(typescript_exports, { getBuildOrderFromAnyBuildOrder: () => getBuildOrderFromAnyBuildOrder, getBuilderCreationParameters: () => getBuilderCreationParameters, getBuilderFileEmit: () => getBuilderFileEmit, + getCanonicalDiagnostic: () => getCanonicalDiagnostic, getCheckFlags: () => getCheckFlags, getClassExtendsHeritageElement: () => getClassExtendsHeritageElement, getClassLikeDeclarationOfSymbol: () => getClassLikeDeclarationOfSymbol, @@ -724,11 +731,11 @@ __export(typescript_exports, { getDeclaredExpandoInitializer: () => getDeclaredExpandoInitializer, getDecorators: () => getDecorators, getDefaultCompilerOptions: () => getDefaultCompilerOptions2, - getDefaultExportInfoWorker: () => getDefaultExportInfoWorker, getDefaultFormatCodeSettings: () => getDefaultFormatCodeSettings, getDefaultLibFileName: () => getDefaultLibFileName, getDefaultLibFilePath: () => getDefaultLibFilePath, getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, + getDefaultLikeExportNameFromDeclaration: () => getDefaultLikeExportNameFromDeclaration, getDefaultResolutionModeForFileWorker: () => getDefaultResolutionModeForFileWorker, getDiagnosticText: () => getDiagnosticText, getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, @@ -1063,6 +1070,7 @@ __export(typescript_exports, { getSwitchedType: () => getSwitchedType, getSymbolId: () => getSymbolId, getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, + getSymbolParentOrFail: () => getSymbolParentOrFail, getSymbolTarget: () => getSymbolTarget, getSyntacticClassifications: () => getSyntacticClassifications, getSyntacticModifierFlags: () => getSyntacticModifierFlags, @@ -1894,7 +1902,6 @@ __export(typescript_exports, { loadWithModeAwareCache: () => loadWithModeAwareCache, makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, makeImport: () => makeImport, - makeImportIfNecessary: () => makeImportIfNecessary, makeStringLiteral: () => makeStringLiteral, mangleScopedPackageName: () => mangleScopedPackageName, map: () => map, @@ -1928,7 +1935,9 @@ __export(typescript_exports, { moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations, moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports, moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules, + moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier, moduleSpecifiers: () => ts_moduleSpecifiers_exports, + moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier, moveEmitHelpers: () => moveEmitHelpers, moveRangeEnd: () => moveRangeEnd, moveRangePastDecorators: () => moveRangePastDecorators, @@ -2008,6 +2017,7 @@ __export(typescript_exports, { parsePackageName: () => parsePackageName, parsePseudoBigInt: () => parsePseudoBigInt, parseValidBigInt: () => parseValidBigInt, + pasteEdits: () => ts_PasteEdits_exports, patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory, pathContainsNodeModules: () => pathContainsNodeModules, pathIsAbsolute: () => pathIsAbsolute, @@ -2444,8 +2454,7 @@ function intersperse(input, element) { } const result = []; for (let i = 0, n = input.length; i < n; i++) { - if (i) - result.push(element); + if (i) result.push(element); result.push(input[i]); } return result; @@ -2461,8 +2470,7 @@ function every(array, callback) { return true; } function find(array, predicate, startIndex) { - if (array === void 0) - return void 0; + if (array === void 0) return void 0; for (let i = startIndex ?? 0; i < array.length; i++) { const value = array[i]; if (predicate(value, i)) { @@ -2472,8 +2480,7 @@ function find(array, predicate, startIndex) { return void 0; } function findLast(array, predicate, startIndex) { - if (array === void 0) - return void 0; + if (array === void 0) return void 0; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { const value = array[i]; if (predicate(value, i)) { @@ -2483,8 +2490,7 @@ function findLast(array, predicate, startIndex) { return void 0; } function findIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; + if (array === void 0) return -1; for (let i = startIndex ?? 0; i < array.length; i++) { if (predicate(array[i], i)) { return i; @@ -2493,8 +2499,7 @@ function findIndex(array, predicate, startIndex) { return -1; } function findLastIndex(array, predicate, startIndex) { - if (array === void 0) - return -1; + if (array === void 0) return -1; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { if (predicate(array[i], i)) { return i; @@ -2548,8 +2553,7 @@ function filter(array, f) { if (array) { const len = array.length; let i = 0; - while (i < len && f(array[i])) - i++; + while (i < len && f(array[i])) i++; if (i < len) { const result = array.slice(0, i); i++; @@ -2658,8 +2662,7 @@ function flatMapToMutable(array, mapfn) { function* flatMapIterator(iter, mapfn) { for (const x of iter) { const iter2 = mapfn(x); - if (!iter2) - continue; + if (!iter2) continue; yield* iter2; } } @@ -2818,14 +2821,11 @@ function getRangesWhere(arr, pred, cb) { } } } - if (start !== void 0) - cb(start, arr.length); + if (start !== void 0) cb(start, arr.length); } function concatenate(array1, array2) { - if (!some(array2)) - return array1; - if (!some(array1)) - return array2; + if (!some(array2)) return array1; + if (!some(array1)) return array2; return [...array1, ...array2]; } function selectIndex(_, i) { @@ -2861,8 +2861,7 @@ function deduplicate(array, equalityComparer, comparer) { return array.length === 0 ? [] : array.length === 1 ? array.slice() : comparer ? deduplicateRelational(array, equalityComparer, comparer) : deduplicateEquality(array, equalityComparer); } function deduplicateSorted(array, comparer) { - if (array.length === 0) - return emptyArray; + if (array.length === 0) return emptyArray; let last2 = array[0]; const deduplicated = [last2]; for (let i = 1; i < array.length; i++) { @@ -2881,13 +2880,23 @@ function deduplicateSorted(array, comparer) { function createSortedArray() { return []; } -function insertSorted(array, insert, compare, allowDuplicates) { +function insertSorted(array, insert, compare, equalityComparer, allowDuplicates) { if (array.length === 0) { array.push(insert); return true; } const insertIndex = binarySearch(array, insert, identity, compare); if (insertIndex < 0) { + if (equalityComparer && !allowDuplicates) { + const idx = ~insertIndex; + if (idx > 0 && equalityComparer(insert, array[idx - 1])) { + return false; + } + if (idx < array.length && equalityComparer(insert, array[idx])) { + array.splice(idx, 1, insert); + return true; + } + } array.splice(~insertIndex, 0, insert); return true; } @@ -2901,8 +2910,7 @@ function sortAndDeduplicate(array, comparer, equalityComparer) { return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive); } function arrayIsSorted(array, comparer) { - if (array.length < 2) - return true; + if (array.length < 2) return true; for (let i = 1, len = array.length; i < len; i++) { if (comparer(array[i - 1], array[i]) === 1 /* GreaterThan */) { return false; @@ -2942,8 +2950,7 @@ function compact(array) { return result || array; } function relativeComplement(arrayA, arrayB, comparer) { - if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) - return arrayB; + if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB; const result = []; loopB: for (let offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) { @@ -2969,32 +2976,24 @@ function relativeComplement(arrayA, arrayB, comparer) { return result; } function append(to, value) { - if (value === void 0) - return to; - if (to === void 0) - return [value]; + if (value === void 0) return to; + if (to === void 0) return [value]; to.push(value); return to; } function combine(xs, ys) { - if (xs === void 0) - return ys; - if (ys === void 0) - return xs; - if (isArray(xs)) - return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); - if (isArray(ys)) - return append(ys, xs); + if (xs === void 0) return ys; + if (ys === void 0) return xs; + if (isArray(xs)) return isArray(ys) ? concatenate(xs, ys) : append(xs, ys); + if (isArray(ys)) return append(ys, xs); return [xs, ys]; } function toOffset(array, offset) { return offset < 0 ? array.length + offset : offset; } function addRange(to, from, start, end) { - if (from === void 0 || from.length === 0) - return to; - if (to === void 0) - return from.slice(start, end); + if (from === void 0 || from.length === 0) return to; + if (to === void 0) return from.slice(start, end); start = start === void 0 ? 0 : toOffset(from, start); end = end === void 0 ? from.length : toOffset(from, end); for (let i = start; i < end && i < from.length; i++) { @@ -3194,8 +3193,7 @@ function arrayFrom(iterator, map2) { } function assign(t, ...args) { for (const arg of args) { - if (arg === void 0) - continue; + if (arg === void 0) continue; for (const p in arg) { if (hasProperty(arg, p)) { t[p] = arg[p]; @@ -3205,22 +3203,17 @@ function assign(t, ...args) { return t; } function equalOwnProperties(left, right, equalityComparer = equateValues) { - if (left === right) - return true; - if (!left || !right) - return false; + if (left === right) return true; + if (!left || !right) return false; for (const key in left) { if (hasOwnProperty.call(left, key)) { - if (!hasOwnProperty.call(right, key)) - return false; - if (!equalityComparer(left[key], right[key])) - return false; + if (!hasOwnProperty.call(right, key)) return false; + if (!equalityComparer(left[key], right[key])) return false; } } for (const key in right) { if (hasOwnProperty.call(right, key)) { - if (!hasOwnProperty.call(left, key)) - return false; + if (!hasOwnProperty.call(left, key)) return false; } } return true; @@ -3229,8 +3222,7 @@ function arrayToMap(array, makeKey, makeValue = identity) { const result = /* @__PURE__ */ new Map(); for (const value of array) { const key = makeKey(value); - if (key !== void 0) - result.set(key, makeValue(value)); + if (key !== void 0) result.set(key, makeValue(value)); } return result; } @@ -3369,11 +3361,9 @@ function createSet(getHashCode, equals) { const set = { has(element) { const hash = getHashCode(element); - if (!multiMap.has(hash)) - return false; + if (!multiMap.has(hash)) return false; const candidates = multiMap.get(hash); - if (!isArray(candidates)) - return equals(candidates, element); + if (!isArray(candidates)) return equals(candidates, element); for (const candidate of candidates) { if (equals(candidate, element)) { return true; @@ -3405,8 +3395,7 @@ function createSet(getHashCode, equals) { }, delete(element) { const hash = getHashCode(element); - if (!multiMap.has(hash)) - return false; + if (!multiMap.has(hash)) return false; const candidates = multiMap.get(hash); if (isArray(candidates)) { for (let i = 0; i < candidates.length; i++) { @@ -3485,8 +3474,7 @@ function tryCast(value, test) { return value !== void 0 && test(value) ? value : void 0; } function cast(value, test) { - if (value !== void 0 && test(value)) - return value; + if (value !== void 0 && test(value)) return value; return Debug.fail(`Invalid cast. The supplied value ${value} did not pass the test '${Debug.getFunctionName(test)}'.`); } function noop(_) { @@ -3604,23 +3592,17 @@ function min(items, compare) { return reduceLeft(items, (x, y) => compare(x, y) === -1 /* LessThan */ ? x : y); } function compareStringsCaseInsensitive(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; a = a.toUpperCase(); b = b.toUpperCase(); return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; } function compareStringsCaseInsensitiveEslintCompatible(a, b) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; a = a.toLowerCase(); b = b.toLowerCase(); return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */; @@ -3634,12 +3616,9 @@ function getStringComparer(ignoreCase) { var createUIStringComparer = /* @__PURE__ */ (() => { return createIntlCollatorStringComparer; function compareWithCallback(a, b, comparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; const value = comparer(a, b); return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -4274,6 +4253,15 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, ); } Debug2.formatNodeFlags = formatNodeFlags; + function formatNodeCheckFlags(flags) { + return formatEnum( + flags, + NodeCheckFlags, + /*isFlags*/ + true + ); + } + Debug2.formatNodeCheckFlags = formatNodeCheckFlags; function formatModifierFlags(flags) { return formatEnum( flags, @@ -4456,8 +4444,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, } Debug2.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo; function enableDebugInfo() { - if (isDebugInfoEnabled) - return; + if (isDebugInfoEnabled) return; const weakTypeTextMap = /* @__PURE__ */ new WeakMap(); const weakNodeTextMap = /* @__PURE__ */ new WeakMap(); Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, { @@ -4566,8 +4553,7 @@ Node ${formatSyntaxKind(node.kind)} was unexpected.`, }, __debugGetText: { value(includeTrivia) { - if (nodeIsSynthesized(this)) - return ""; + if (nodeIsSynthesized(this)) return ""; let text = weakNodeTextMap.get(this); if (text === void 0) { const parseNode = getParseTreeNode(this); @@ -4797,8 +4783,7 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; node.endLane = lane; const children = getChildren(node); for (let i = 0; i < children.length; i++) { - if (i > 0) - lane++; + if (i > 0) lane++; const child = children[i]; computeLanes(child, lane); if (child.endLane > node.endLane) { @@ -4809,28 +4794,17 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; } } function getHeader2(flags) { - if (flags & 2 /* Start */) - return "Start"; - if (flags & 4 /* BranchLabel */) - return "Branch"; - if (flags & 8 /* LoopLabel */) - return "Loop"; - if (flags & 16 /* Assignment */) - return "Assignment"; - if (flags & 32 /* TrueCondition */) - return "True"; - if (flags & 64 /* FalseCondition */) - return "False"; - if (flags & 128 /* SwitchClause */) - return "SwitchClause"; - if (flags & 256 /* ArrayMutation */) - return "ArrayMutation"; - if (flags & 512 /* Call */) - return "Call"; - if (flags & 1024 /* ReduceLabel */) - return "ReduceLabel"; - if (flags & 1 /* Unreachable */) - return "Unreachable"; + if (flags & 2 /* Start */) return "Start"; + if (flags & 4 /* BranchLabel */) return "Branch"; + if (flags & 8 /* LoopLabel */) return "Loop"; + if (flags & 16 /* Assignment */) return "Assignment"; + if (flags & 32 /* TrueCondition */) return "True"; + if (flags & 64 /* FalseCondition */) return "False"; + if (flags & 128 /* SwitchClause */) return "SwitchClause"; + if (flags & 256 /* ArrayMutation */) return "ArrayMutation"; + if (flags & 512 /* Call */) return "Call"; + if (flags & 1024 /* ReduceLabel */) return "ReduceLabel"; + if (flags & 1 /* Unreachable */) return "Unreachable"; throw new Error(); } function getNodeText(node) { @@ -4878,12 +4852,9 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; for (let i = 0; i < children.length; i++) { const child = children[i]; let connector = 8 /* Right */; - if (child.lane === node.lane) - connector |= 4 /* Left */; - if (i > 0) - connector |= 1 /* Up */; - if (i < children.length - 1) - connector |= 2 /* Down */; + if (child.lane === node.lane) connector |= 4 /* Left */; + if (i > 0) connector |= 1 /* Up */; + if (i < children.length - 1) connector |= 2 /* Down */; connectors[node.level][child.lane] |= connector; } if (children.length === 0) { @@ -4893,10 +4864,8 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; for (let i = 0; i < parents.length; i++) { const parent2 = parents[i]; let connector = 4 /* Left */; - if (i > 0) - connector |= 1 /* Up */; - if (i < parents.length - 1) - connector |= 2 /* Down */; + if (i > 0) connector |= 1 /* Up */; + if (i < parents.length - 1) connector |= 2 /* Down */; connectors[node.level - 1][parent2.lane] |= connector; } } @@ -4906,10 +4875,8 @@ m2: ${this.mapper2.__debugToString().split("\n").join("\n ")}`; const above = lane > 0 ? connectors[column][lane - 1] : 0; let connector = connectors[column][lane]; if (!connector) { - if (left & 8 /* Right */) - connector |= 12 /* LeftRight */; - if (above & 2 /* Down */) - connector |= 3 /* UpDown */; + if (left & 8 /* Right */) connector |= 12 /* LeftRight */; + if (above & 2 /* Down */) connector |= 3 /* UpDown */; connectors[column][lane] = connector; } } @@ -5020,16 +4987,13 @@ var _Version = class _Version { } static tryParse(text) { const result = tryParseComponents(text); - if (!result) - return void 0; + if (!result) return void 0; const { major, minor, patch, prerelease, build: build2 } = result; return new _Version(major, minor, patch, prerelease, build2); } compareTo(other) { - if (this === other) - return 0 /* EqualTo */; - if (other === void 0) - return 1 /* GreaterThan */; + if (this === other) return 0 /* EqualTo */; + if (other === void 0) return 1 /* GreaterThan */; return compareValues(this.major, other.major) || compareValues(this.minor, other.minor) || compareValues(this.patch, other.patch) || comparePrereleaseIdentifiers(this.prerelease, other.prerelease); } increment(field) { @@ -5056,10 +5020,8 @@ var _Version = class _Version { } toString() { let result = `${this.major}.${this.minor}.${this.patch}`; - if (some(this.prerelease)) - result += `-${this.prerelease.join(".")}`; - if (some(this.build)) - result += `+${this.build.join(".")}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; return result; } }; @@ -5067,13 +5029,10 @@ _Version.zero = new _Version(0, 0, 0, ["0"]); var Version = _Version; function tryParseComponents(text) { const match = versionRegExp.exec(text); - if (!match) - return void 0; + if (!match) return void 0; const [, major, minor = "0", patch = "0", prerelease = "", build2 = ""] = match; - if (prerelease && !prereleaseRegExp.test(prerelease)) - return void 0; - if (build2 && !buildRegExp.test(build2)) - return void 0; + if (prerelease && !prereleaseRegExp.test(prerelease)) return void 0; + if (build2 && !buildRegExp.test(build2)) return void 0; return { major: parseInt(major, 10), minor: parseInt(minor, 10), @@ -5083,30 +5042,23 @@ function tryParseComponents(text) { }; } function comparePrereleaseIdentifiers(left, right) { - if (left === right) - return 0 /* EqualTo */; - if (left.length === 0) - return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; - if (right.length === 0) - return -1 /* LessThan */; + if (left === right) return 0 /* EqualTo */; + if (left.length === 0) return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */; + if (right.length === 0) return -1 /* LessThan */; const length2 = Math.min(left.length, right.length); for (let i = 0; i < length2; i++) { const leftIdentifier = left[i]; const rightIdentifier = right[i]; - if (leftIdentifier === rightIdentifier) - continue; + if (leftIdentifier === rightIdentifier) continue; const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); if (leftIsNumeric || rightIsNumeric) { - if (leftIsNumeric !== rightIsNumeric) - return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */; const result = compareValues(+leftIdentifier, +rightIdentifier); - if (result) - return result; + if (result) return result; } else { const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); - if (result) - return result; + if (result) return result; } } return compareValues(left.length, right.length); @@ -5129,8 +5081,7 @@ var VersionRange = class _VersionRange { * in `node-semver`. */ test(version2) { - if (typeof version2 === "string") - version2 = new Version(version2); + if (typeof version2 === "string") version2 = new Version(version2); return testDisjunction(version2, this._alternatives); } toString() { @@ -5145,19 +5096,16 @@ var rangeRegExp = /^(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; function parseRange(text) { const alternatives = []; for (let range of text.trim().split(logicalOrRegExp)) { - if (!range) - continue; + if (!range) continue; const comparators = []; range = range.trim(); const match = hyphenRegExp.exec(range); if (match) { - if (!parseHyphen(match[1], match[2], comparators)) - return void 0; + if (!parseHyphen(match[1], match[2], comparators)) return void 0; } else { for (const simple of range.split(whitespaceRegExp)) { const match2 = rangeRegExp.exec(simple.trim()); - if (!match2 || !parseComparator(match2[1], match2[2], comparators)) - return void 0; + if (!match2 || !parseComparator(match2[1], match2[2], comparators)) return void 0; } } alternatives.push(comparators); @@ -5166,8 +5114,7 @@ function parseRange(text) { } function parsePartial(text) { const match = partialRegExp.exec(text); - if (!match) - return void 0; + if (!match) return void 0; const [, major, minor = "*", patch = "*", prerelease, build2] = match; const version2 = new Version( isWildcard(major) ? 0 : parseInt(major, 10), @@ -5180,11 +5127,9 @@ function parsePartial(text) { } function parseHyphen(left, right, comparators) { const leftResult = parsePartial(left); - if (!leftResult) - return false; + if (!leftResult) return false; const rightResult = parsePartial(right); - if (!rightResult) - return false; + if (!rightResult) return false; if (!isWildcard(leftResult.major)) { comparators.push(createComparator(">=", leftResult.version)); } @@ -5197,8 +5142,7 @@ function parseHyphen(left, right, comparators) { } function parseComparator(operator, text, comparators) { const result = parsePartial(text); - if (!result) - return false; + if (!result) return false; const { version: version2, major, minor, patch } = result; if (!isWildcard(major)) { switch (operator) { @@ -5256,18 +5200,15 @@ function createComparator(operator, operand) { return { operator, operand }; } function testDisjunction(version2, alternatives) { - if (alternatives.length === 0) - return true; + if (alternatives.length === 0) return true; for (const alternative of alternatives) { - if (testAlternative(version2, alternative)) - return true; + if (testAlternative(version2, alternative)) return true; } return false; } function testAlternative(version2, comparators) { for (const comparator of comparators) { - if (!testComparator(version2, comparator.operator, comparator.operand)) - return false; + if (!testComparator(version2, comparator.operator, comparator.operand)) return false; } return true; } @@ -5320,8 +5261,7 @@ function tryGetPerformance() { } function tryGetPerformanceHooks() { const p = tryGetPerformance(); - if (!p) - return void 0; + if (!p) return void 0; const { shouldWriteNativeEvents, performance: performance2 } = p; const hooks = { shouldWriteNativeEvents, @@ -5437,10 +5377,8 @@ function forEachMark(cb) { marks.forEach((_time, markName) => cb(markName)); } function clearMeasures(name) { - if (name !== void 0) - durations.delete(name); - else - durations.clear(); + if (name !== void 0) durations.delete(name); + else durations.clear(); performanceImpl == null ? void 0 : performanceImpl.clearMeasures(name); } function clearMarks(name) { @@ -5602,15 +5540,12 @@ var tracingEnabled; } } function writeEvent(eventType, phase, name, args, extras, time = 1e3 * timestamp()) { - if (mode === "server" && phase === "checkTypes" /* CheckTypes */) - return; + if (mode === "server" && phase === "checkTypes" /* CheckTypes */) return; mark("beginTracing"); fs.writeSync(traceFd, `, {"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); - if (extras) - fs.writeSync(traceFd, `,${extras}`); - if (args) - fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); + if (extras) fs.writeSync(traceFd, `,${extras}`); + if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); fs.writeSync(traceFd, `}`); mark("endTracing"); measure("Tracing", "beginTracing", "endTracing"); @@ -6275,7 +6210,7 @@ var RegularExpressionFlags = /* @__PURE__ */ ((RegularExpressionFlags2) => { RegularExpressionFlags2[RegularExpressionFlags2["Unicode"] = 32] = "Unicode"; RegularExpressionFlags2[RegularExpressionFlags2["UnicodeSets"] = 64] = "UnicodeSets"; RegularExpressionFlags2[RegularExpressionFlags2["Sticky"] = 128] = "Sticky"; - RegularExpressionFlags2[RegularExpressionFlags2["UnicodeMode"] = 96] = "UnicodeMode"; + RegularExpressionFlags2[RegularExpressionFlags2["AnyUnicodeMode"] = 96] = "AnyUnicodeMode"; RegularExpressionFlags2[RegularExpressionFlags2["Modifiers"] = 28] = "Modifiers"; return RegularExpressionFlags2; })(RegularExpressionFlags || {}); @@ -6342,7 +6277,7 @@ var FileIncludeKind = /* @__PURE__ */ ((FileIncludeKind2) => { return FileIncludeKind2; })(FileIncludeKind || {}); var FilePreprocessingDiagnosticsKind = /* @__PURE__ */ ((FilePreprocessingDiagnosticsKind2) => { - FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic"; + FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["FilePreprocessingLibReferenceDiagnostic"] = 0] = "FilePreprocessingLibReferenceDiagnostic"; FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic"; FilePreprocessingDiagnosticsKind2[FilePreprocessingDiagnosticsKind2["ResolutionDiagnostics"] = 2] = "ResolutionDiagnostics"; return FilePreprocessingDiagnosticsKind2; @@ -6378,6 +6313,12 @@ var UnionReduction = /* @__PURE__ */ ((UnionReduction2) => { UnionReduction2[UnionReduction2["Subtype"] = 2] = "Subtype"; return UnionReduction2; })(UnionReduction || {}); +var IntersectionFlags = /* @__PURE__ */ ((IntersectionFlags2) => { + IntersectionFlags2[IntersectionFlags2["None"] = 0] = "None"; + IntersectionFlags2[IntersectionFlags2["NoSupertypeReduction"] = 1] = "NoSupertypeReduction"; + IntersectionFlags2[IntersectionFlags2["NoConstraintReduction"] = 2] = "NoConstraintReduction"; + return IntersectionFlags2; +})(IntersectionFlags || {}); var ContextFlags = /* @__PURE__ */ ((ContextFlags3) => { ContextFlags3[ContextFlags3["None"] = 0] = "None"; ContextFlags3[ContextFlags3["Signature"] = 1] = "Signature"; @@ -6417,6 +6358,7 @@ var NodeBuilderFlags = /* @__PURE__ */ ((NodeBuilderFlags2) => { NodeBuilderFlags2[NodeBuilderFlags2["NoSyntacticPrinter"] = -2147483648] = "NoSyntacticPrinter"; NodeBuilderFlags2[NodeBuilderFlags2["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths"; NodeBuilderFlags2[NodeBuilderFlags2["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain"; + NodeBuilderFlags2[NodeBuilderFlags2["AllowUnresolvedNames"] = 1] = "AllowUnresolvedNames"; NodeBuilderFlags2[NodeBuilderFlags2["IgnoreErrors"] = 70221824] = "IgnoreErrors"; NodeBuilderFlags2[NodeBuilderFlags2["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags2[NodeBuilderFlags2["InTypeAlias"] = 8388608] = "InTypeAlias"; @@ -6464,6 +6406,7 @@ var SymbolAccessibility = /* @__PURE__ */ ((SymbolAccessibility2) => { SymbolAccessibility2[SymbolAccessibility2["Accessible"] = 0] = "Accessible"; SymbolAccessibility2[SymbolAccessibility2["NotAccessible"] = 1] = "NotAccessible"; SymbolAccessibility2[SymbolAccessibility2["CannotBeNamed"] = 2] = "CannotBeNamed"; + SymbolAccessibility2[SymbolAccessibility2["NotResolved"] = 3] = "NotResolved"; return SymbolAccessibility2; })(SymbolAccessibility || {}); var SyntheticSymbolKind = /* @__PURE__ */ ((SyntheticSymbolKind2) => { @@ -6561,11 +6504,6 @@ var SymbolFlags = /* @__PURE__ */ ((SymbolFlags3) => { SymbolFlags3[SymbolFlags3["LateBindingContainer"] = 6256] = "LateBindingContainer"; return SymbolFlags3; })(SymbolFlags || {}); -var EnumKind = /* @__PURE__ */ ((EnumKind2) => { - EnumKind2[EnumKind2["Numeric"] = 0] = "Numeric"; - EnumKind2[EnumKind2["Literal"] = 1] = "Literal"; - return EnumKind2; -})(EnumKind || {}); var CheckFlags = /* @__PURE__ */ ((CheckFlags2) => { CheckFlags2[CheckFlags2["None"] = 0] = "None"; CheckFlags2[CheckFlags2["Instantiated"] = 1] = "Instantiated"; @@ -6616,32 +6554,33 @@ var InternalSymbolName = /* @__PURE__ */ ((InternalSymbolName2) => { InternalSymbolName2["ImportAttributes"] = "__importAttributes"; return InternalSymbolName2; })(InternalSymbolName || {}); -var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags2) => { - NodeCheckFlags2[NodeCheckFlags2["None"] = 0] = "None"; - NodeCheckFlags2[NodeCheckFlags2["TypeChecked"] = 1] = "TypeChecked"; - NodeCheckFlags2[NodeCheckFlags2["LexicalThis"] = 2] = "LexicalThis"; - NodeCheckFlags2[NodeCheckFlags2["CaptureThis"] = 4] = "CaptureThis"; - NodeCheckFlags2[NodeCheckFlags2["CaptureNewTarget"] = 8] = "CaptureNewTarget"; - NodeCheckFlags2[NodeCheckFlags2["SuperInstance"] = 16] = "SuperInstance"; - NodeCheckFlags2[NodeCheckFlags2["SuperStatic"] = 32] = "SuperStatic"; - NodeCheckFlags2[NodeCheckFlags2["ContextChecked"] = 64] = "ContextChecked"; - NodeCheckFlags2[NodeCheckFlags2["MethodWithSuperPropertyAccessInAsync"] = 128] = "MethodWithSuperPropertyAccessInAsync"; - NodeCheckFlags2[NodeCheckFlags2["MethodWithSuperPropertyAssignmentInAsync"] = 256] = "MethodWithSuperPropertyAssignmentInAsync"; - NodeCheckFlags2[NodeCheckFlags2["CaptureArguments"] = 512] = "CaptureArguments"; - NodeCheckFlags2[NodeCheckFlags2["EnumValuesComputed"] = 1024] = "EnumValuesComputed"; - NodeCheckFlags2[NodeCheckFlags2["LexicalModuleMergesWithClass"] = 2048] = "LexicalModuleMergesWithClass"; - NodeCheckFlags2[NodeCheckFlags2["LoopWithCapturedBlockScopedBinding"] = 4096] = "LoopWithCapturedBlockScopedBinding"; - NodeCheckFlags2[NodeCheckFlags2["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; - NodeCheckFlags2[NodeCheckFlags2["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; - NodeCheckFlags2[NodeCheckFlags2["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; - NodeCheckFlags2[NodeCheckFlags2["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; - NodeCheckFlags2[NodeCheckFlags2["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; - NodeCheckFlags2[NodeCheckFlags2["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ConstructorReference"] = 536870912] = "ConstructorReference"; - NodeCheckFlags2[NodeCheckFlags2["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; - NodeCheckFlags2[NodeCheckFlags2["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; - NodeCheckFlags2[NodeCheckFlags2["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; - return NodeCheckFlags2; +var NodeCheckFlags = /* @__PURE__ */ ((NodeCheckFlags3) => { + NodeCheckFlags3[NodeCheckFlags3["None"] = 0] = "None"; + NodeCheckFlags3[NodeCheckFlags3["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags3[NodeCheckFlags3["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags3[NodeCheckFlags3["CaptureNewTarget"] = 8] = "CaptureNewTarget"; + NodeCheckFlags3[NodeCheckFlags3["SuperInstance"] = 16] = "SuperInstance"; + NodeCheckFlags3[NodeCheckFlags3["SuperStatic"] = 32] = "SuperStatic"; + NodeCheckFlags3[NodeCheckFlags3["ContextChecked"] = 64] = "ContextChecked"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAccessInAsync"] = 128] = "MethodWithSuperPropertyAccessInAsync"; + NodeCheckFlags3[NodeCheckFlags3["MethodWithSuperPropertyAssignmentInAsync"] = 256] = "MethodWithSuperPropertyAssignmentInAsync"; + NodeCheckFlags3[NodeCheckFlags3["CaptureArguments"] = 512] = "CaptureArguments"; + NodeCheckFlags3[NodeCheckFlags3["EnumValuesComputed"] = 1024] = "EnumValuesComputed"; + NodeCheckFlags3[NodeCheckFlags3["LexicalModuleMergesWithClass"] = 2048] = "LexicalModuleMergesWithClass"; + NodeCheckFlags3[NodeCheckFlags3["LoopWithCapturedBlockScopedBinding"] = 4096] = "LoopWithCapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["ContainsCapturedBlockScopeBinding"] = 8192] = "ContainsCapturedBlockScopeBinding"; + NodeCheckFlags3[NodeCheckFlags3["CapturedBlockScopedBinding"] = 16384] = "CapturedBlockScopedBinding"; + NodeCheckFlags3[NodeCheckFlags3["BlockScopedBindingInLoop"] = 32768] = "BlockScopedBindingInLoop"; + NodeCheckFlags3[NodeCheckFlags3["NeedsLoopOutParameter"] = 65536] = "NeedsLoopOutParameter"; + NodeCheckFlags3[NodeCheckFlags3["AssignmentsMarked"] = 131072] = "AssignmentsMarked"; + NodeCheckFlags3[NodeCheckFlags3["ContainsConstructorReference"] = 262144] = "ContainsConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ConstructorReference"] = 536870912] = "ConstructorReference"; + NodeCheckFlags3[NodeCheckFlags3["ContainsClassWithPrivateIdentifiers"] = 1048576] = "ContainsClassWithPrivateIdentifiers"; + NodeCheckFlags3[NodeCheckFlags3["ContainsSuperPropertyInStaticInitializer"] = 2097152] = "ContainsSuperPropertyInStaticInitializer"; + NodeCheckFlags3[NodeCheckFlags3["InCheckIdentifier"] = 4194304] = "InCheckIdentifier"; + NodeCheckFlags3[NodeCheckFlags3["LazyFlags"] = 539358128] = "LazyFlags"; + return NodeCheckFlags3; })(NodeCheckFlags || {}); var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["Any"] = 1] = "Any"; @@ -6674,6 +6613,7 @@ var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["TemplateLiteral"] = 134217728] = "TemplateLiteral"; TypeFlags2[TypeFlags2["StringMapping"] = 268435456] = "StringMapping"; TypeFlags2[TypeFlags2["Reserved1"] = 536870912] = "Reserved1"; + TypeFlags2[TypeFlags2["Reserved2"] = 1073741824] = "Reserved2"; TypeFlags2[TypeFlags2["AnyOrUnknown"] = 3] = "AnyOrUnknown"; TypeFlags2[TypeFlags2["Nullable"] = 98304] = "Nullable"; TypeFlags2[TypeFlags2["Literal"] = 2944] = "Literal"; @@ -6712,6 +6652,7 @@ var TypeFlags = /* @__PURE__ */ ((TypeFlags2) => { TypeFlags2[TypeFlags2["IncludesEmptyObject"] = 16777216 /* Conditional */] = "IncludesEmptyObject"; TypeFlags2[TypeFlags2["IncludesInstantiable"] = 33554432 /* Substitution */] = "IncludesInstantiable"; TypeFlags2[TypeFlags2["IncludesConstrainedTypeVariable"] = 536870912 /* Reserved1 */] = "IncludesConstrainedTypeVariable"; + TypeFlags2[TypeFlags2["IncludesError"] = 1073741824 /* Reserved2 */] = "IncludesError"; TypeFlags2[TypeFlags2["NotPrimitiveUnion"] = 36323331] = "NotPrimitiveUnion"; return TypeFlags2; })(TypeFlags || {}); @@ -7013,6 +6954,7 @@ var WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags3) => { return WatchDirectoryFlags3; })(WatchDirectoryFlags || {}); var CharacterCodes = /* @__PURE__ */ ((CharacterCodes2) => { + CharacterCodes2[CharacterCodes2["EOF"] = -1] = "EOF"; CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes2[CharacterCodes2["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed"; @@ -7285,12 +7227,15 @@ var LanguageFeatureMinimumTarget = /* @__PURE__ */ ((LanguageFeatureMinimumTarge LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ArrowFunctions"] = 2 /* ES2015 */] = "ArrowFunctions"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BlockScopedVariables"] = 2 /* ES2015 */] = "BlockScopedVariables"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ObjectAssign"] = 2 /* ES2015 */] = "ObjectAssign"; + LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsUnicode"] = 2 /* ES2015 */] = "RegularExpressionFlagsUnicode"; + LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsSticky"] = 2 /* ES2015 */] = "RegularExpressionFlagsSticky"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["Exponentiation"] = 3 /* ES2016 */] = "Exponentiation"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncFunctions"] = 4 /* ES2017 */] = "AsyncFunctions"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ForAwaitOf"] = 5 /* ES2018 */] = "ForAwaitOf"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncGenerators"] = 5 /* ES2018 */] = "AsyncGenerators"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncIteration"] = 5 /* ES2018 */] = "AsyncIteration"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ObjectSpreadRest"] = 5 /* ES2018 */] = "ObjectSpreadRest"; + LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsDotAll"] = 5 /* ES2018 */] = "RegularExpressionFlagsDotAll"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BindinglessCatch"] = 6 /* ES2019 */] = "BindinglessCatch"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BigInt"] = 7 /* ES2020 */] = "BigInt"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["NullishCoalesce"] = 7 /* ES2020 */] = "NullishCoalesce"; @@ -7299,9 +7244,11 @@ var LanguageFeatureMinimumTarget = /* @__PURE__ */ ((LanguageFeatureMinimumTarge LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["TopLevelAwait"] = 9 /* ES2022 */] = "TopLevelAwait"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ClassFields"] = 9 /* ES2022 */] = "ClassFields"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["PrivateNamesAndClassStaticBlocks"] = 9 /* ES2022 */] = "PrivateNamesAndClassStaticBlocks"; + LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsHasIndices"] = 9 /* ES2022 */] = "RegularExpressionFlagsHasIndices"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ShebangComments"] = 99 /* ESNext */] = "ShebangComments"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["UsingAndAwaitUsing"] = 99 /* ESNext */] = "UsingAndAwaitUsing"; LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ClassAndClassElementDecorators"] = 99 /* ESNext */] = "ClassAndClassElementDecorators"; + LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsUnicodeSets"] = 99 /* ESNext */] = "RegularExpressionFlagsUnicodeSets"; return LanguageFeatureMinimumTarget2; })(LanguageFeatureMinimumTarget || {}); var ExternalEmitHelpers = /* @__PURE__ */ ((ExternalEmitHelpers2) => { @@ -7754,8 +7701,7 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFi dirName, 1 /* Directory */, (eventName, relativeFileName) => { - if (!isString(relativeFileName)) - return; + if (!isString(relativeFileName)) return; const fileName = getNormalizedAbsolutePath(relativeFileName, dirName); const filePath = toCanonicalName(fileName); const callbacks = fileName && fileWatcherCallbacks.get(filePath); @@ -7766,15 +7712,12 @@ function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFi const existingTime = fileTimestamps.get(filePath); if (eventName === "change") { currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime; - if (currentModifiedTime.getTime() === existingTime.getTime()) - return; + if (currentModifiedTime.getTime() === existingTime.getTime()) return; } currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileName) || missingFileModifiedTime); fileTimestamps.set(filePath, currentModifiedTime); - if (existingTime === missingFileModifiedTime) - eventKind = 0 /* Created */; - else if (currentModifiedTime === missingFileModifiedTime) - eventKind = 2 /* Deleted */; + if (existingTime === missingFileModifiedTime) eventKind = 0 /* Created */; + else if (currentModifiedTime === missingFileModifiedTime) eventKind = 2 /* Deleted */; } for (const fileCallback of callbacks) { fileCallback(fileName, eventKind, currentModifiedTime); @@ -7817,8 +7760,7 @@ function createFixedChunkSizePollingWatchFile(host) { scheduleNextPoll(); } function scheduleNextPoll() { - if (!watchedFiles.length || pollScheduled) - return; + if (!watchedFiles.length || pollScheduled) return; pollScheduled = host.setTimeout(pollQueue, 2e3 /* High */, "pollQueue"); } } @@ -7843,10 +7785,8 @@ function createSingleWatcherPerName(cache, useCaseSensitiveFileNames2, name, cal return { close: () => { const watcher = cache.get(path); - if (!watcher) - return; - if (!orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) - return; + if (!watcher) return; + if (!orderedRemoveItem(watcher.callbacks, callback) || watcher.callbacks.length) return; cache.delete(path); closeFileWatcherOf(watcher); } @@ -7901,11 +7841,9 @@ function createDirectoryWatcherSupportingRecursive({ dirName, (fileName) => { var _a; - if (isIgnoredPath(fileName, options)) - return; + if (isIgnoredPath(fileName, options)) return; if (options == null ? void 0 : options.synchronousWatchDirectory) { - if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) - invokeCallbacks(dirName, dirPath, fileName); + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, fileName); updateChildWatches(dirName, dirPath, options); } else { nonSyncUpdateChildWatches(dirName, dirPath, fileName, options); @@ -7923,8 +7861,7 @@ function createDirectoryWatcherSupportingRecursive({ cache.set(dirPath, directoryWatcher); updateChildWatches(dirName, dirPath, options); } - if (link) - (directoryWatcher.links ?? (directoryWatcher.links = /* @__PURE__ */ new Set())).add(link); + if (link) (directoryWatcher.links ?? (directoryWatcher.links = /* @__PURE__ */ new Set())).add(link); const callbackToAdd = callback && { dirName, callback }; if (callbackToAdd) { callbackCache.add(dirPath, callbackToAdd); @@ -7934,13 +7871,10 @@ function createDirectoryWatcherSupportingRecursive({ close: () => { var _a; const directoryWatcher2 = Debug.checkDefined(cache.get(dirPath)); - if (callbackToAdd) - callbackCache.remove(dirPath, callbackToAdd); - if (link) - (_a = directoryWatcher2.links) == null ? void 0 : _a.delete(link); + if (callbackToAdd) callbackCache.remove(dirPath, callbackToAdd); + if (link) (_a = directoryWatcher2.links) == null ? void 0 : _a.delete(link); directoryWatcher2.refCount--; - if (directoryWatcher2.refCount) - return; + if (directoryWatcher2.refCount) return; cache.delete(dirPath); directoryWatcher2.links = void 0; closeFileWatcherOf(directoryWatcher2); @@ -7959,8 +7893,7 @@ function createDirectoryWatcherSupportingRecursive({ invokeMap = fileNameOrInvokeMap; } callbackCache.forEach((callbacks, rootDirName) => { - if (invokeMap && invokeMap.get(rootDirName) === true) - return; + if (invokeMap && invokeMap.get(rootDirName) === true) return; if (rootDirName === dirPath || startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === directorySeparator) { if (invokeMap) { if (fileNames) { @@ -8022,8 +7955,7 @@ function createDirectoryWatcherSupportingRecursive({ const { value: [dirPath, { dirName, options, fileNames }] } = result; cacheToUpdateChildWatches.delete(dirPath); const hasChanges = updateChildWatches(dirName, dirPath, options); - if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) - invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames); + if (!((_a = cache.get(dirPath)) == null ? void 0 : _a.targetWatcher)) invokeCallbacks(dirName, dirPath, invokeMap, hasChanges ? void 0 : fileNames); } sysLog(`sysLog:: invokingWatchers:: Elapsed:: ${timestamp() - start}ms:: ${cacheToUpdateChildWatches.size}`); callbackCache.forEach((callbacks, rootDirName) => { @@ -8042,8 +7974,7 @@ function createDirectoryWatcherSupportingRecursive({ sysLog(`sysLog:: Elapsed:: ${elapsed}ms:: onTimerToUpdateChildWatches:: ${cacheToUpdateChildWatches.size} ${timerToUpdateChildWatches}`); } function removeChildWatches(parentWatcher) { - if (!parentWatcher) - return; + if (!parentWatcher) return; const existingChildWatches = parentWatcher.childWatches; parentWatcher.childWatches = emptyArray; for (const childWatcher of existingChildWatches) { @@ -8059,8 +7990,7 @@ function createDirectoryWatcherSupportingRecursive({ } function updateChildWatches(parentDir, parentDirPath, options) { const parentWatcher = cache.get(parentDirPath); - if (!parentWatcher) - return false; + if (!parentWatcher) return false; const target = normalizePath(realpath(parentDir)); let hasChanges; let newChildWatches; @@ -8105,10 +8035,8 @@ function createDirectoryWatcherSupportingRecursive({ return some(ignoredPaths, (searchPath) => isInPath(path, searchPath)) || isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames2, getCurrentDirectory); } function isInPath(path, searchPath) { - if (path.includes(searchPath)) - return true; - if (useCaseSensitiveFileNames2) - return false; + if (path.includes(searchPath)) return true; + if (useCaseSensitiveFileNames2) return false; return toCanonicalFilePath(path).includes(searchPath); } } @@ -8237,8 +8165,7 @@ function createSystemWatchFunctions({ return fixedChunkSizePollingWatchFile || (fixedChunkSizePollingWatchFile = createFixedChunkSizePollingWatchFile({ getModifiedTime: getModifiedTime3, setTimeout: setTimeout2 })); } function updateOptionsForWatchFile(options, useNonPollingWatchers2) { - if (options && options.watchFile !== void 0) - return options; + if (options && options.watchFile !== void 0) return options; switch (tscWatchFile) { case "PriorityPollingInterval": return { watchFile: 1 /* PriorityPollingInterval */ }; @@ -8336,8 +8263,7 @@ function createSystemWatchFunctions({ } } function updateOptionsForWatchDirectory(options) { - if (options && options.watchDirectory !== void 0) - return options; + if (options && options.watchDirectory !== void 0) return options; switch (tscWatchDirectory) { case "RecursiveDirectoryUsingFsWatchFile": return { watchDirectory: 1 /* FixedPollingInterval */ }; @@ -8422,8 +8348,7 @@ function createSystemWatchFunctions({ } if (event === "rename" && (!relativeName || relativeName === lastDirectoryPart || endsWith(relativeName, lastDirectoryPartWithDirectorySeparator))) { const modifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; - if (originalRelativeName) - callback(event, originalRelativeName, modifiedTime); + if (originalRelativeName) callback(event, originalRelativeName, modifiedTime); callback(event, relativeName, modifiedTime); if (inodeWatching) { updateWatcher(modifiedTime === missingFileModifiedTime ? watchMissingFileSystemEntry : watchPresentFileSystemEntry); @@ -8431,8 +8356,7 @@ function createSystemWatchFunctions({ updateWatcher(watchMissingFileSystemEntry); } } else { - if (originalRelativeName) - callback(event, originalRelativeName); + if (originalRelativeName) callback(event, originalRelativeName); callback(event, relativeName); } } @@ -8466,8 +8390,7 @@ function createSystemWatchFunctions({ return fsWatchWorker(fileOrDirectory, recursive, (eventName, relativeFileName, currentModifiedTime) => { if (eventName === "change") { currentModifiedTime || (currentModifiedTime = getModifiedTime3(fileOrDirectory) || missingFileModifiedTime); - if (currentModifiedTime.getTime() === modifiedTime.getTime()) - return; + if (currentModifiedTime.getTime() === modifiedTime.getTime()) return; } modifiedTime = currentModifiedTime || getModifiedTime3(fileOrDirectory) || missingFileModifiedTime; callback(eventName, relativeFileName, modifiedTime); @@ -8989,33 +8912,26 @@ function isVolumeCharacter(charCode) { } function getFileUrlVolumeSeparatorEnd(url, start) { const ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; + if (ch0 === 58 /* colon */) return start + 1; if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { const ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) return start + 3; } return -1; } function getEncodedRootLength(path) { - if (!path) - return 0; + if (!path) return 0; const ch0 = path.charCodeAt(0); if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; + if (path.charCodeAt(1) !== ch0) return 1; const p1 = path.indexOf(ch0 === 47 /* slash */ ? directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; + if (p1 < 0) return path.length; return p1 + 1; } if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { const ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; - if (path.length === 2) - return 2; + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) return 3; + if (path.length === 2) return 2; } const schemeEnd = path.indexOf(urlSchemeSeparator); if (schemeEnd !== -1) { @@ -9048,24 +8964,21 @@ function getRootLength(path) { function getDirectoryPath(path) { path = normalizeSlashes(path); const rootLength = getRootLength(path); - if (rootLength === path.length) - return path; + if (rootLength === path.length) return path; path = removeTrailingDirectorySeparator(path); return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); } function getBaseFileName(path, extensions, ignoreCase) { path = normalizeSlashes(path); const rootLength = getRootLength(path); - if (rootLength === path.length) - return ""; + if (rootLength === path.length) return ""; path = removeTrailingDirectorySeparator(path); const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1)); const extension = extensions !== void 0 && ignoreCase !== void 0 ? getAnyExtensionFromPath(name, extensions, ignoreCase) : void 0; return extension ? name.slice(0, name.length - extension.length) : name; } function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { - if (!startsWith(extension, ".")) - extension = "." + extension; + if (!startsWith(extension, ".")) extension = "." + extension; if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { const pathExtension = path.slice(path.length - extension.length); if (stringEqualityComparer(pathExtension, extension)) { @@ -9079,8 +8992,7 @@ function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) } for (const extension of extensions) { const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); - if (result) - return result; + if (result) return result; } return ""; } @@ -9098,8 +9010,7 @@ function getAnyExtensionFromPath(path, extensions, ignoreCase) { function pathComponents(path, rootLength) { const root = path.substring(0, rootLength); const rest = path.substring(rootLength).split(directorySeparator); - if (rest.length && !lastOrUndefined(rest)) - rest.pop(); + if (rest.length && !lastOrUndefined(rest)) rest.pop(); return [root, ...rest]; } function getPathComponents(path, currentDirectory = "") { @@ -9107,8 +9018,7 @@ function getPathComponents(path, currentDirectory = "") { return pathComponents(path, getRootLength(path)); } function getPathFromPathComponents(pathComponents2, length2) { - if (pathComponents2.length === 0) - return ""; + if (pathComponents2.length === 0) return ""; const root = pathComponents2[0] && ensureTrailingDirectorySeparator(pathComponents2[0]); return root + pathComponents2.slice(1, length2).join(directorySeparator); } @@ -9116,34 +9026,28 @@ function normalizeSlashes(path) { return path.includes("\\") ? path.replace(backslashRegExp, directorySeparator) : path; } function reducePathComponents(components) { - if (!some(components)) - return []; + if (!some(components)) return []; const reduced = [components[0]]; for (let i = 1; i < components.length; i++) { const component = components[i]; - if (!component) - continue; - if (component === ".") - continue; + 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; + } else if (reduced[0]) continue; } reduced.push(component); } return reduced; } function combinePaths(path, ...paths) { - if (path) - path = normalizeSlashes(path); + if (path) path = normalizeSlashes(path); for (let relativePath of paths) { - if (!relativePath) - continue; + if (!relativePath) continue; relativePath = normalizeSlashes(relativePath); if (!path || getRootLength(relativePath) !== 0) { path = relativePath; @@ -9178,8 +9082,7 @@ function normalizePath(path) { return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; } function getPathWithoutRoot(pathComponents2) { - if (pathComponents2.length === 0) - return ""; + if (pathComponents2.length === 0) return ""; return pathComponents2.slice(1).join(directorySeparator); } function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { @@ -9217,12 +9120,9 @@ function changeFullExtension(path, newExtension) { } var relativePathSegmentRegExp = /(?:\/\/)|(?:^|\/)\.\.?(?:$|\/)/; function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === void 0) - return -1 /* LessThan */; - if (b === void 0) - return 1 /* GreaterThan */; + if (a === b) return 0 /* EqualTo */; + if (a === void 0) return -1 /* LessThan */; + if (b === void 0) return 1 /* GreaterThan */; const aRoot = a.substring(0, getRootLength(a)); const bRoot = b.substring(0, getRootLength(b)); const result = compareStringsCaseInsensitive(aRoot, bRoot); @@ -9267,10 +9167,8 @@ function containsPath(parent2, child, currentDirectory, ignoreCase) { } else if (typeof currentDirectory === "boolean") { ignoreCase = currentDirectory; } - if (parent2 === void 0 || child === void 0) - return false; - if (parent2 === child) - return true; + if (parent2 === void 0 || child === void 0) return false; + if (parent2 === child) return true; const parentComponents = reducePathComponents(getPathComponents(parent2)); const childComponents = reducePathComponents(getPathComponents(child)); if (childComponents.length < parentComponents.length) { @@ -9298,8 +9196,7 @@ function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanoni const fromComponent = getCanonicalFileName(fromComponents[start]); const toComponent = getCanonicalFileName(toComponents[start]); const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; + if (!comparer(fromComponent, toComponent)) break; } if (start === 0) { return toComponents; @@ -9800,7 +9697,7 @@ var Diagnostics = { Range_out_of_order_in_character_class: diag(1517, 1 /* Error */, "Range_out_of_order_in_character_class_1517", "Range out of order in character class."), Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class: diag(1518, 1 /* Error */, "Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_characte_1518", "Anything that would possibly match more than a single character is invalid inside a negated character class."), Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead: diag(1519, 1 /* Error */, "Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead_1519", "Operators must not be mixed within a character class. Wrap it in a nested class instead."), - Expected_a_class_set_oprand: diag(1520, 1 /* Error */, "Expected_a_class_set_oprand_1520", "Expected a class set oprand."), + Expected_a_class_set_operand: diag(1520, 1 /* Error */, "Expected_a_class_set_operand_1520", "Expected a class set operand."), q_must_be_followed_by_string_alternatives_enclosed_in_braces: diag(1521, 1 /* Error */, "q_must_be_followed_by_string_alternatives_enclosed_in_braces_1521", "'\\q' must be followed by string alternatives enclosed in braces."), A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash: diag(1522, 1 /* Error */, "A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backs_1522", "A character class must not contain a reserved double punctuator. Did you mean to escape it with backslash?"), Expected_a_Unicode_property_name: diag(1523, 1 /* Error */, "Expected_a_Unicode_property_name_1523", "Expected a Unicode property name."), @@ -9814,8 +9711,10 @@ var Diagnostics = { _0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces: diag(1531, 1 /* Error */, "_0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces_1531", "'\\{0}' must be followed by a Unicode property value expression enclosed in braces."), There_is_no_capturing_group_named_0_in_this_regular_expression: diag(1532, 1 /* Error */, "There_is_no_capturing_group_named_0_in_this_regular_expression_1532", "There is no capturing group named '{0}' in this regular expression."), This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression: diag(1533, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_r_1533", "This backreference refers to a group that does not exist. There are only {0} capturing groups in this regular expression."), - This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups: diag(1534, 1 /* Error */, "This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups_1534", "This backreference is invalid because the containing regular expression contains no capturing groups."), + This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression: diag(1534, 1 /* Error */, "This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regul_1534", "This backreference refers to a group that does not exist. There are no capturing groups in this regular expression."), This_character_cannot_be_escaped_in_a_regular_expression: diag(1535, 1 /* Error */, "This_character_cannot_be_escaped_in_a_regular_expression_1535", "This character cannot be escaped in a regular expression."), + Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead: diag(1536, 1 /* Error */, "Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended__1536", "Octal escape sequences and backreferences are not allowed in a character class. If this was intended as an escape sequence, use the syntax '{0}' instead."), + Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class: diag(1537, 1 /* Error */, "Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_1537", "Decimal escape sequences and backreferences are not allowed in a character class."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag( @@ -10457,7 +10356,6 @@ var Diagnostics = { Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1: diag(4083, 1 /* Error */, "Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1_4083", "Type parameter '{0}' of exported type alias has or is using private name '{1}'."), Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2: diag(4084, 1 /* Error */, "Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2_4084", "Exported type alias '{0}' has or is using private name '{1}' from module {2}."), Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1: diag(4085, 1 /* Error */, "Extends_clause_for_inferred_type_0_has_or_is_using_private_name_1_4085", "Extends clause for inferred type '{0}' has or is using private name '{1}'."), - Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict: diag(4090, 1 /* Error */, "Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_librar_4090", "Conflicting definitions for '{0}' found at '{1}' and '{2}'. Consider installing a specific version of this library to resolve the conflict."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2: diag(4091, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2_4091", "Parameter '{0}' of index signature from exported interface has or is using name '{1}' from private module '{2}'."), Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1: diag(4092, 1 /* Error */, "Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1_4092", "Parameter '{0}' of index signature from exported interface has or is using private name '{1}'."), Property_0_of_exported_class_expression_may_not_be_private_or_protected: diag(4094, 1 /* Error */, "Property_0_of_exported_class_expression_may_not_be_private_or_protected_4094", "Property '{0}' of exported class expression may not be private or protected."), @@ -11064,6 +10962,7 @@ var Diagnostics = { Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files: diag(6719, 3 /* Message */, "Require_sufficient_annotation_on_exports_so_other_tools_can_trivially_generate_declaration_files_6719", "Require sufficient annotation on exports so other tools can trivially generate declaration files."), Default_catch_clause_variables_as_unknown_instead_of_any: diag(6803, 3 /* Message */, "Default_catch_clause_variables_as_unknown_instead_of_any_6803", "Default catch clause variables as 'unknown' instead of 'any'."), Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_in_the_output_file_s_format_based_on_the_module_setting: diag(6804, 3 /* Message */, "Do_not_transform_or_elide_any_imports_or_exports_not_marked_as_type_only_ensuring_they_are_written_i_6804", "Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting."), + Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported: diag(6805, 3 /* Message */, "Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported_6805", "Disable full type checking (only critical parse and emit errors will be reported)."), one_of_Colon: diag(6900, 3 /* Message */, "one_of_Colon_6900", "one of:"), one_or_more_Colon: diag(6901, 3 /* Message */, "one_or_more_Colon_6901", "one or more:"), type_Colon: diag(6902, 3 /* Message */, "type_Colon_6902", "type:"), @@ -11233,6 +11132,8 @@ var Diagnostics = { Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit: diag(9035, 1 /* Error */, "Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit_9035", "Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit."), Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it: diag(9036, 1 /* Error */, "Move_the_expression_in_default_export_to_a_variable_and_add_a_type_annotation_to_it_9036", "Move the expression in default export to a variable and add a type annotation to it."), Default_exports_can_t_be_inferred_with_isolatedDeclarations: diag(9037, 1 /* Error */, "Default_exports_can_t_be_inferred_with_isolatedDeclarations_9037", "Default exports can't be inferred with --isolatedDeclarations."), + Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations: diag(9038, 1 /* Error */, "Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations_9038", "Computed property names on class or object literals cannot be inferred with --isolatedDeclarations."), + Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations: diag(9039, 1 /* Error */, "Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations_9039", "Type containing private name '{0}' can't be used with --isolatedDeclarations."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), JSX_elements_cannot_have_multiple_attributes_with_the_same_name: diag(17001, 1 /* Error */, "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001", "JSX elements cannot have multiple attributes with the same name."), Expected_corresponding_JSX_closing_tag_for_0: diag(17002, 1 /* Error */, "Expected_corresponding_JSX_closing_tag_for_0_17002", "Expected corresponding JSX closing tag for '{0}'."), @@ -11312,6 +11213,16 @@ var Diagnostics = { Export_0_from_module_1: diag(90059, 3 /* Message */, "Export_0_from_module_1_90059", "Export '{0}' from module '{1}'"), Export_all_referenced_locals: diag(90060, 3 /* Message */, "Export_all_referenced_locals_90060", "Export all referenced locals"), Update_modifiers_of_0: diag(90061, 3 /* Message */, "Update_modifiers_of_0_90061", "Update modifiers of '{0}'"), + Add_annotation_of_type_0: diag(90062, 3 /* Message */, "Add_annotation_of_type_0_90062", "Add annotation of type '{0}'"), + Add_return_type_0: diag(90063, 3 /* Message */, "Add_return_type_0_90063", "Add return type '{0}'"), + Extract_base_class_to_variable: diag(90064, 3 /* Message */, "Extract_base_class_to_variable_90064", "Extract base class to variable"), + Extract_default_export_to_variable: diag(90065, 3 /* Message */, "Extract_default_export_to_variable_90065", "Extract default export to variable"), + Extract_binding_expressions_to_variable: diag(90066, 3 /* Message */, "Extract_binding_expressions_to_variable_90066", "Extract binding expressions to variable"), + Add_all_missing_type_annotations: diag(90067, 3 /* Message */, "Add_all_missing_type_annotations_90067", "Add all missing type annotations"), + Add_satisfies_and_an_inline_type_assertion_with_0: diag(90068, 3 /* Message */, "Add_satisfies_and_an_inline_type_assertion_with_0_90068", "Add satisfies and an inline type assertion with '{0}'"), + Extract_to_variable_and_replace_with_0_as_typeof_0: diag(90069, 3 /* Message */, "Extract_to_variable_and_replace_with_0_as_typeof_0_90069", "Extract to variable and replace with '{0} as typeof {0}'"), + Mark_array_literal_as_const: diag(90070, 3 /* Message */, "Mark_array_literal_as_const_90070", "Mark array literal as const"), + Annotate_types_of_properties_expando_function_in_a_namespace: diag(90071, 3 /* Message */, "Annotate_types_of_properties_expando_function_in_a_namespace_90071", "Annotate types of properties expando function in a namespace"), Convert_function_to_an_ES2015_class: diag(95001, 3 /* Message */, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_0_to_1_in_0: diag(95003, 3 /* Message */, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"), Extract_to_0_in_1: diag(95004, 3 /* Message */, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), @@ -11716,19 +11627,16 @@ var charToRegExpFlag = new Map(Object.entries({ y: 128 /* Sticky */ })); var regExpFlagToFirstAvailableLanguageVersion = /* @__PURE__ */ new Map([ - [1 /* HasIndices */, 9 /* ES2022 */], - [2 /* Global */, 0 /* ES3 */], - [4 /* IgnoreCase */, 0 /* ES3 */], - [8 /* Multiline */, 0 /* ES3 */], - [16 /* DotAll */, 5 /* ES2018 */], - [32 /* Unicode */, 2 /* ES2015 */], - [64 /* UnicodeSets */, 99 /* ESNext */], - [128 /* Sticky */, 2 /* ES2015 */] + [1 /* HasIndices */, 9 /* RegularExpressionFlagsHasIndices */], + [16 /* DotAll */, 5 /* RegularExpressionFlagsDotAll */], + [32 /* Unicode */, 2 /* RegularExpressionFlagsUnicode */], + [64 /* UnicodeSets */, 99 /* RegularExpressionFlagsUnicodeSets */], + [128 /* Sticky */, 2 /* RegularExpressionFlagsSticky */] ]); var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; -var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2208, 2228, 2230, 2237, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69376, 69404, 69415, 69415, 69424, 69445, 69600, 69622, 69635, 69687, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70751, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71680, 71723, 71840, 71903, 71935, 71935, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 123136, 123180, 123191, 123197, 123214, 123214, 123584, 123627, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101]; -var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2208, 2228, 2230, 2237, 2259, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3328, 3331, 3333, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7673, 7675, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40943, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42943, 42946, 42950, 42999, 43047, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43879, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 67072, 67382, 67392, 67413, 67424, 67431, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69376, 69404, 69415, 69415, 69424, 69456, 69600, 69622, 69632, 69702, 69734, 69743, 69759, 69818, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69958, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70096, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70206, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70751, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71680, 71738, 71840, 71913, 71935, 71935, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72384, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73728, 74649, 74752, 74862, 74880, 75075, 77824, 78894, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101106, 110592, 110878, 110928, 110930, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123584, 123641, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, 194560, 195101, 917760, 917999]; +var unicodeESNextIdentifierStart = [65, 90, 97, 122, 170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 895, 895, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1488, 1514, 1519, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2144, 2154, 2160, 2183, 2185, 2190, 2208, 2249, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2432, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2556, 2556, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2809, 2809, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3133, 3133, 3160, 3162, 3165, 3165, 3168, 3169, 3200, 3200, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3293, 3294, 3296, 3297, 3313, 3314, 3332, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3412, 3414, 3423, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5905, 5919, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6264, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6430, 6480, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6988, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7401, 7404, 7406, 7411, 7413, 7414, 7418, 7418, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12443, 12447, 12449, 12538, 12540, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42653, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43261, 43262, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43488, 43492, 43494, 43503, 43514, 43518, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43646, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66335, 66349, 66378, 66384, 66421, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68096, 68112, 68115, 68117, 68119, 68121, 68149, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68324, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68899, 69248, 69289, 69296, 69297, 69376, 69404, 69415, 69415, 69424, 69445, 69488, 69505, 69552, 69572, 69600, 69622, 69635, 69687, 69745, 69746, 69749, 69749, 69763, 69807, 69840, 69864, 69891, 69926, 69956, 69956, 69959, 69959, 69968, 70002, 70006, 70006, 70019, 70066, 70081, 70084, 70106, 70106, 70108, 70108, 70144, 70161, 70163, 70187, 70207, 70208, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70366, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70461, 70461, 70480, 70480, 70493, 70497, 70656, 70708, 70727, 70730, 70751, 70753, 70784, 70831, 70852, 70853, 70855, 70855, 71040, 71086, 71128, 71131, 71168, 71215, 71236, 71236, 71296, 71338, 71352, 71352, 71424, 71450, 71488, 71494, 71680, 71723, 71840, 71903, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71983, 71999, 71999, 72001, 72001, 72096, 72103, 72106, 72144, 72161, 72161, 72163, 72163, 72192, 72192, 72203, 72242, 72250, 72250, 72272, 72272, 72284, 72329, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72750, 72768, 72768, 72818, 72847, 72960, 72966, 72968, 72969, 72971, 73008, 73030, 73030, 73056, 73061, 73063, 73064, 73066, 73097, 73112, 73112, 73440, 73458, 73474, 73474, 73476, 73488, 73490, 73523, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78913, 78918, 82944, 83526, 92160, 92728, 92736, 92766, 92784, 92862, 92880, 92909, 92928, 92975, 92992, 92995, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94032, 94032, 94099, 94111, 94176, 94177, 94179, 94179, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 122624, 122654, 122661, 122666, 122928, 122989, 123136, 123180, 123191, 123197, 123214, 123214, 123536, 123565, 123584, 123627, 124112, 124139, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125184, 125251, 125259, 125259, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743]; +var unicodeESNextIdentifierPart = [48, 57, 65, 90, 95, 95, 97, 122, 170, 170, 181, 181, 183, 183, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 895, 895, 902, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1327, 1329, 1366, 1369, 1369, 1376, 1416, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1519, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2045, 2045, 2048, 2093, 2112, 2139, 2144, 2154, 2160, 2183, 2185, 2190, 2200, 2273, 2275, 2403, 2406, 2415, 2417, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2556, 2556, 2558, 2558, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2809, 2815, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2901, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3072, 3084, 3086, 3088, 3090, 3112, 3114, 3129, 3132, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3162, 3165, 3165, 3168, 3171, 3174, 3183, 3200, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3293, 3294, 3296, 3299, 3302, 3311, 3313, 3315, 3328, 3340, 3342, 3344, 3346, 3396, 3398, 3400, 3402, 3406, 3412, 3415, 3423, 3427, 3430, 3439, 3450, 3455, 3457, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3558, 3567, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3718, 3722, 3724, 3747, 3749, 3749, 3751, 3773, 3776, 3780, 3782, 3782, 3784, 3790, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4969, 4977, 4992, 5007, 5024, 5109, 5112, 5117, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5880, 5888, 5909, 5919, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6159, 6169, 6176, 6264, 6272, 6314, 6320, 6389, 6400, 6430, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6618, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6832, 6845, 6847, 6862, 6912, 6988, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7296, 7304, 7312, 7354, 7357, 7359, 7376, 7378, 7380, 7418, 7424, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8472, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12447, 12449, 12543, 12549, 12591, 12593, 12686, 12704, 12735, 12784, 12799, 13312, 19903, 19968, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42737, 42775, 42783, 42786, 42888, 42891, 42954, 42960, 42961, 42963, 42963, 42965, 42969, 42994, 43047, 43052, 43052, 43072, 43123, 43136, 43205, 43216, 43225, 43232, 43255, 43259, 43259, 43261, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43488, 43518, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43824, 43866, 43868, 43881, 43888, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65071, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594, 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786, 65856, 65908, 66045, 66045, 66176, 66204, 66208, 66256, 66272, 66272, 66304, 66335, 66349, 66378, 66384, 66426, 66432, 66461, 66464, 66499, 66504, 66511, 66513, 66517, 66560, 66717, 66720, 66729, 66736, 66771, 66776, 66811, 66816, 66855, 66864, 66915, 66928, 66938, 66940, 66954, 66956, 66962, 66964, 66965, 66967, 66977, 66979, 66993, 66995, 67001, 67003, 67004, 67072, 67382, 67392, 67413, 67424, 67431, 67456, 67461, 67463, 67504, 67506, 67514, 67584, 67589, 67592, 67592, 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669, 67680, 67702, 67712, 67742, 67808, 67826, 67828, 67829, 67840, 67861, 67872, 67897, 67968, 68023, 68030, 68031, 68096, 68099, 68101, 68102, 68108, 68115, 68117, 68119, 68121, 68149, 68152, 68154, 68159, 68159, 68192, 68220, 68224, 68252, 68288, 68295, 68297, 68326, 68352, 68405, 68416, 68437, 68448, 68466, 68480, 68497, 68608, 68680, 68736, 68786, 68800, 68850, 68864, 68903, 68912, 68921, 69248, 69289, 69291, 69292, 69296, 69297, 69373, 69404, 69415, 69415, 69424, 69456, 69488, 69509, 69552, 69572, 69600, 69622, 69632, 69702, 69734, 69749, 69759, 69818, 69826, 69826, 69840, 69864, 69872, 69881, 69888, 69940, 69942, 69951, 69956, 69959, 69968, 70003, 70006, 70006, 70016, 70084, 70089, 70092, 70094, 70106, 70108, 70108, 70144, 70161, 70163, 70199, 70206, 70209, 70272, 70278, 70280, 70280, 70282, 70285, 70287, 70301, 70303, 70312, 70320, 70378, 70384, 70393, 70400, 70403, 70405, 70412, 70415, 70416, 70419, 70440, 70442, 70448, 70450, 70451, 70453, 70457, 70459, 70468, 70471, 70472, 70475, 70477, 70480, 70480, 70487, 70487, 70493, 70499, 70502, 70508, 70512, 70516, 70656, 70730, 70736, 70745, 70750, 70753, 70784, 70853, 70855, 70855, 70864, 70873, 71040, 71093, 71096, 71104, 71128, 71133, 71168, 71232, 71236, 71236, 71248, 71257, 71296, 71352, 71360, 71369, 71424, 71450, 71453, 71467, 71472, 71481, 71488, 71494, 71680, 71738, 71840, 71913, 71935, 71942, 71945, 71945, 71948, 71955, 71957, 71958, 71960, 71989, 71991, 71992, 71995, 72003, 72016, 72025, 72096, 72103, 72106, 72151, 72154, 72161, 72163, 72164, 72192, 72254, 72263, 72263, 72272, 72345, 72349, 72349, 72368, 72440, 72704, 72712, 72714, 72758, 72760, 72768, 72784, 72793, 72818, 72847, 72850, 72871, 72873, 72886, 72960, 72966, 72968, 72969, 72971, 73014, 73018, 73018, 73020, 73021, 73023, 73031, 73040, 73049, 73056, 73061, 73063, 73064, 73066, 73102, 73104, 73105, 73107, 73112, 73120, 73129, 73440, 73462, 73472, 73488, 73490, 73530, 73534, 73538, 73552, 73561, 73648, 73648, 73728, 74649, 74752, 74862, 74880, 75075, 77712, 77808, 77824, 78895, 78912, 78933, 82944, 83526, 92160, 92728, 92736, 92766, 92768, 92777, 92784, 92862, 92864, 92873, 92880, 92909, 92912, 92916, 92928, 92982, 92992, 92995, 93008, 93017, 93027, 93047, 93053, 93071, 93760, 93823, 93952, 94026, 94031, 94087, 94095, 94111, 94176, 94177, 94179, 94180, 94192, 94193, 94208, 100343, 100352, 101589, 101632, 101640, 110576, 110579, 110581, 110587, 110589, 110590, 110592, 110882, 110898, 110898, 110928, 110930, 110933, 110933, 110948, 110951, 110960, 111355, 113664, 113770, 113776, 113788, 113792, 113800, 113808, 113817, 113821, 113822, 118528, 118573, 118576, 118598, 119141, 119145, 119149, 119154, 119163, 119170, 119173, 119179, 119210, 119213, 119362, 119364, 119808, 119892, 119894, 119964, 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980, 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069, 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121, 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144, 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570, 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686, 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779, 120782, 120831, 121344, 121398, 121403, 121452, 121461, 121461, 121476, 121476, 121499, 121503, 121505, 121519, 122624, 122654, 122661, 122666, 122880, 122886, 122888, 122904, 122907, 122913, 122915, 122916, 122918, 122922, 122928, 122989, 123023, 123023, 123136, 123180, 123184, 123197, 123200, 123209, 123214, 123214, 123536, 123566, 123584, 123641, 124112, 124153, 124896, 124902, 124904, 124907, 124909, 124910, 124912, 124926, 124928, 125124, 125136, 125142, 125184, 125259, 125264, 125273, 126464, 126467, 126469, 126495, 126497, 126498, 126500, 126500, 126503, 126503, 126505, 126514, 126516, 126519, 126521, 126521, 126523, 126523, 126530, 126530, 126535, 126535, 126537, 126537, 126539, 126539, 126541, 126543, 126545, 126546, 126548, 126548, 126551, 126551, 126553, 126553, 126555, 126555, 126557, 126557, 126559, 126559, 126561, 126562, 126564, 126564, 126567, 126570, 126572, 126578, 126580, 126583, 126585, 126588, 126590, 126590, 126592, 126601, 126603, 126619, 126625, 126627, 126629, 126633, 126635, 126651, 130032, 130041, 131072, 173791, 173824, 177977, 177984, 178205, 178208, 183969, 183984, 191456, 191472, 192093, 194560, 195101, 196608, 201546, 201552, 205743, 917760, 917999]; var commentDirectiveRegExSingleLine = /^\/\/\/?\s*@(ts-expect-error|ts-ignore)/; var commentDirectiveRegExMultiLine = /^(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/; var jsDocSeeOrLink = /@(?:see|link)/i; @@ -11848,8 +11756,7 @@ function computeLineOfPosition(lineStarts, position, lowerBound) { return lineNumber; } function getLinesBetweenPositions(sourceFile, pos1, pos2) { - if (pos1 === pos2) - return 0; + if (pos1 === pos2) return 0; const lineStarts = getLineStarts(sourceFile); const lower = Math.min(pos1, pos2); const isNegative = lower === pos2; @@ -12312,6 +12219,18 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan }); } return scanner2; + function codePointUnchecked(pos2) { + return codePointAt(text, pos2); + } + function codePointChecked(pos2) { + return pos2 >= 0 && pos2 < end ? codePointUnchecked(pos2) : -1 /* EOF */; + } + function charCodeUnchecked(pos2) { + return text.charCodeAt(pos2); + } + function charCodeChecked(pos2) { + return pos2 >= 0 && pos2 < end ? charCodeUnchecked(pos2) : -1 /* EOF */; + } function error2(message, errPos = pos, length3, arg0) { if (onError) { const oldPos = pos; @@ -12326,7 +12245,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let isPreviousTokenSeparator = false; let result = ""; while (true) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (allowSeparator) { @@ -12353,7 +12272,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } break; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { tokenFlags |= 16384 /* ContainsInvalidSeparator */; error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } @@ -12362,9 +12281,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanNumber() { let start2 = pos; let mainFragment; - if (text.charCodeAt(pos) === 48 /* _0 */) { + if (charCodeUnchecked(pos) === 48 /* _0 */) { pos++; - if (text.charCodeAt(pos) === 95 /* _ */) { + if (charCodeUnchecked(pos) === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */ | 16384 /* ContainsInvalidSeparator */; error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1); pos--; @@ -12379,8 +12298,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 32 /* Octal */; const withMinus = token === 41 /* MinusToken */; const literal = (withMinus ? "-" : "") + "0o" + (+tokenValue).toString(8); - if (withMinus) - start2--; + if (withMinus) start2--; error2(Diagnostics.Octal_literals_are_not_allowed_Use_the_syntax_0, start2, pos - start2, literal); return 9 /* NumericLiteral */; } @@ -12389,16 +12307,15 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } let decimalFragment; let scientificFragment; - if (text.charCodeAt(pos) === 46 /* dot */) { + if (charCodeUnchecked(pos) === 46 /* dot */) { pos++; decimalFragment = scanNumberFragment(); } let end2 = pos; - if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) { + if (charCodeUnchecked(pos) === 69 /* E */ || charCodeUnchecked(pos) === 101 /* e */) { pos++; tokenFlags |= 16 /* Scientific */; - if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */) - pos++; + if (charCodeUnchecked(pos) === 43 /* plus */ || charCodeUnchecked(pos) === 45 /* minus */) pos++; const preNumericPart = pos; const finalFragment = scanNumberFragment(); if (!finalFragment) { @@ -12437,7 +12354,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } } function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { - if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) { + if (!isIdentifierStart(codePointUnchecked(pos), languageVersion)) { return; } const identifierStart = pos; @@ -12456,8 +12373,8 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanDigits() { const start2 = pos; let isOctal = true; - while (isDigit(text.charCodeAt(pos))) { - if (!isOctalDigit(text.charCodeAt(pos))) { + while (isDigit(charCodeChecked(pos))) { + if (!isOctalDigit(charCodeUnchecked(pos))) { isOctal = false; } pos++; @@ -12489,7 +12406,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let allowSeparator = false; let isPreviousTokenSeparator = false; while (valueChars.length < minCount || scanAsManyAsPossible) { - let ch = text.charCodeAt(pos); + let ch = charCodeUnchecked(pos); if (canHaveSeparators && ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (allowSeparator) { @@ -12516,13 +12433,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (valueChars.length < minCount) { valueChars = []; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } return String.fromCharCode(...valueChars); } function scanString(jsxAttributeString = false) { - const quote2 = text.charCodeAt(pos); + const quote2 = charCodeUnchecked(pos); pos++; let result = ""; let start2 = pos; @@ -12533,7 +12450,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan error2(Diagnostics.Unterminated_string_literal); break; } - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === quote2) { result += text.substring(start2, pos); pos++; @@ -12541,12 +12458,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (ch === 92 /* backslash */ && !jsxAttributeString) { result += text.substring(start2, pos); - result += scanEscapeSequence( - /*shouldEmitInvalidEscapeError*/ - true, - /*isRegularExpression*/ - false - ); + result += scanEscapeSequence(1 /* String */ | 2 /* ReportErrors */); start2 = pos; continue; } @@ -12561,7 +12473,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return result; } function scanTemplateAndSetTokenValue(shouldEmitInvalidEscapeError) { - const startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */; + const startedWithBacktick = charCodeUnchecked(pos) === 96 /* backtick */; pos++; let start2 = pos; let contents = ""; @@ -12574,14 +12486,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; break; } - const currChar = text.charCodeAt(pos); + const currChar = charCodeUnchecked(pos); if (currChar === 96 /* backtick */) { contents += text.substring(start2, pos); pos++; resultingToken = startedWithBacktick ? 15 /* NoSubstitutionTemplateLiteral */ : 18 /* TemplateTail */; break; } - if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) { + if (currChar === 36 /* $ */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 123 /* openBrace */) { contents += text.substring(start2, pos); pos += 2; resultingToken = startedWithBacktick ? 16 /* TemplateHead */ : 17 /* TemplateMiddle */; @@ -12589,18 +12501,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (currChar === 92 /* backslash */) { contents += text.substring(start2, pos); - contents += scanEscapeSequence( - shouldEmitInvalidEscapeError, - /*isRegularExpression*/ - false - ); + contents += scanEscapeSequence(1 /* String */ | (shouldEmitInvalidEscapeError ? 2 /* ReportErrors */ : 0)); start2 = pos; continue; } if (currChar === 13 /* carriageReturn */) { contents += text.substring(start2, pos); pos++; - if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } contents += "\n"; @@ -12613,37 +12521,39 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = contents; return resultingToken; } - function scanEscapeSequence(shouldEmitInvalidEscapeError, isRegularExpression) { + function scanEscapeSequence(flags) { const start2 = pos; pos++; if (pos >= end) { error2(Diagnostics.Unexpected_end_of_text); return ""; } - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); pos++; switch (ch) { case 48 /* _0 */: - if (pos >= end || !isDigit(text.charCodeAt(pos))) { + if (pos >= end || !isDigit(charCodeUnchecked(pos))) { return "\0"; } case 49 /* _1 */: case 50 /* _2 */: case 51 /* _3 */: - if (pos < end && isOctalDigit(text.charCodeAt(pos))) { + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { pos++; } case 52 /* _4 */: case 53 /* _5 */: case 54 /* _6 */: case 55 /* _7 */: - if (pos < end && isOctalDigit(text.charCodeAt(pos))) { + if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { pos++; } tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { const code = parseInt(text.substring(start2 + 1, pos), 8); - if (isRegularExpression !== "annex-b") { + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */) && ch !== 48 /* _0 */) { + error2(Diagnostics.Octal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class_If_this_was_intended_as_an_escape_sequence_use_the_syntax_0_instead, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); + } else { error2(Diagnostics.Octal_escape_sequences_are_not_allowed_Use_the_syntax_0, start2, pos - start2, "\\x" + code.toString(16).padStart(2, "0")); } return String.fromCharCode(code); @@ -12652,8 +12562,12 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 56 /* _8 */: case 57 /* _9 */: tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { - error2(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + if (flags & 6 /* ReportInvalidEscapeErrors */) { + if (flags & 4 /* RegularExpression */ && !(flags & 32 /* AtomEscape */)) { + error2(Diagnostics.Decimal_escape_sequences_and_backreferences_are_not_allowed_in_a_character_class, start2, pos - start2); + } else { + error2(Diagnostics.Escape_sequence_0_is_not_allowed, start2, pos - start2, text.substring(start2, pos)); + } return String.fromCharCode(ch); } return text.substring(start2, pos); @@ -12674,14 +12588,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 34 /* doubleQuote */: return '"'; case 117 /* u */: - if ((!isRegularExpression || shouldEmitInvalidEscapeError) && pos < end && text.charCodeAt(pos) === 123 /* openBrace */) { + if (flags & 17 /* ScanExtendedUnicodeEscape */ && pos < end && charCodeUnchecked(pos) === 123 /* openBrace */) { pos -= 2; - return scanExtendedUnicodeEscape(!!isRegularExpression || shouldEmitInvalidEscapeError); + return scanExtendedUnicodeEscape(!!(flags & 6 /* ReportInvalidEscapeErrors */)); } for (; pos < start2 + 6; pos++) { - if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { error2(Diagnostics.Hexadecimal_digit_expected); } return text.substring(start2, pos); @@ -12690,11 +12604,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 1024 /* UnicodeEscape */; const escapedValue = parseInt(text.substring(start2 + 2, pos), 16); const escapedValueString = String.fromCharCode(escapedValue); - if (isRegularExpression && shouldEmitInvalidEscapeError && escapedValue >= 55296 && escapedValue <= 56319 && pos + 6 < end && text.substring(pos, pos + 2) === "\\u" && text.charCodeAt(pos + 2) !== 123 /* openBrace */) { + if (flags & 16 /* AnyUnicodeMode */ && escapedValue >= 55296 && escapedValue <= 56319 && pos + 6 < end && text.substring(pos, pos + 2) === "\\u" && charCodeUnchecked(pos + 2) !== 123 /* openBrace */) { const nextStart = pos; let nextPos = pos + 2; for (; nextPos < nextStart + 6; nextPos++) { - if (!isHexDigit(text.charCodeAt(pos))) { + if (!isHexDigit(charCodeUnchecked(pos))) { return escapedValueString; } } @@ -12707,9 +12621,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return escapedValueString; case 120 /* x */: for (; pos < start2 + 4; pos++) { - if (!(pos < end && isHexDigit(text.charCodeAt(pos)))) { + if (!(pos < end && isHexDigit(charCodeUnchecked(pos)))) { tokenFlags |= 2048 /* ContainsInvalidEscape */; - if (isRegularExpression || shouldEmitInvalidEscapeError) { + if (flags & 6 /* ReportInvalidEscapeErrors */) { error2(Diagnostics.Hexadecimal_digit_expected); } return text.substring(start2, pos); @@ -12718,7 +12632,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 4096 /* HexEscape */; return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); case 13 /* carriageReturn */: - if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) { + if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } case 10 /* lineFeed */: @@ -12726,7 +12640,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan case 8233 /* paragraphSeparator */: return ""; default: - if (isRegularExpression === true && (shouldEmitInvalidEscapeError || isIdentifierPart(ch, languageVersion))) { + if (flags & 16 /* AnyUnicodeMode */ || flags & 4 /* RegularExpression */ && !(flags & 8 /* AnnexB */) && isIdentifierPart(ch, languageVersion)) { error2(Diagnostics.This_character_cannot_be_escaped_in_a_regular_expression, pos - 2, 2); } return String.fromCharCode(ch); @@ -12759,7 +12673,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan error2(Diagnostics.Unexpected_end_of_text); } isInvalidExtendedEscape = true; - } else if (text.charCodeAt(pos) === 125 /* closeBrace */) { + } else if (charCodeUnchecked(pos) === 125 /* closeBrace */) { pos++; } else { if (shouldEmitInvalidEscapeError) { @@ -12775,7 +12689,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return utf16EncodeAsString(escapedValue); } function peekUnicodeEscape() { - if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) { + if (pos + 5 < end && charCodeUnchecked(pos + 1) === 117 /* u */) { const start2 = pos; pos += 2; const value = scanExactNumberOfHexDigits( @@ -12789,7 +12703,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return -1; } function peekExtendedUnicodeEscape() { - if (codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) { + if (codePointUnchecked(pos + 1) === 117 /* u */ && codePointUnchecked(pos + 2) === 123 /* openBrace */) { const start2 = pos; pos += 3; const escapedValueString = scanMinimumNumberOfHexDigits( @@ -12807,7 +12721,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let result = ""; let start2 = pos; while (pos < end) { - let ch = codePointAt(text, pos); + let ch = codePointUnchecked(pos); if (isIdentifierPart(ch, languageVersion)) { pos += charSize(ch); } else if (ch === 92 /* backslash */) { @@ -12854,7 +12768,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let separatorAllowed = false; let isPreviousTokenSeparator = false; while (true) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 95 /* _ */) { tokenFlags |= 512 /* ContainsSeparator */; if (separatorAllowed) { @@ -12876,13 +12790,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; isPreviousTokenSeparator = false; } - if (text.charCodeAt(pos - 1) === 95 /* _ */) { + if (charCodeUnchecked(pos - 1) === 95 /* _ */) { error2(Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1); } return value; } function checkBigIntSuffix() { - if (text.charCodeAt(pos) === 110 /* n */) { + if (charCodeUnchecked(pos) === 110 /* n */) { tokenValue += "n"; if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) { tokenValue = parsePseudoBigInt(tokenValue) + "n"; @@ -12904,7 +12818,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); if (pos === 0) { if (ch === 35 /* hash */ && isShebangTrivia(text, pos)) { pos = scanShebangTrivia(text, pos); @@ -12923,7 +12837,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; continue; } else { - if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) { + if (ch === 13 /* carriageReturn */ && pos + 1 < end && charCodeUnchecked(pos + 1) === 10 /* lineFeed */) { pos += 2; } else { pos++; @@ -12956,14 +12870,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; continue; } else { - while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { pos++; } return token = 5 /* WhitespaceTrivia */; } case 33 /* exclamation */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 38 /* ExclamationEqualsEqualsToken */; } return pos += 2, token = 36 /* ExclamationEqualsToken */; @@ -12980,19 +12894,19 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan false ); case 37 /* percent */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 70 /* PercentEqualsToken */; } pos++; return token = 45 /* PercentToken */; case 38 /* ampersand */: - if (text.charCodeAt(pos + 1) === 38 /* ampersand */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 38 /* ampersand */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 77 /* AmpersandAmpersandEqualsToken */; } return pos += 2, token = 56 /* AmpersandAmpersandToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 74 /* AmpersandEqualsToken */; } pos++; @@ -13004,11 +12918,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 22 /* CloseParenToken */; case 42 /* asterisk */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 67 /* AsteriskEqualsToken */; } - if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 68 /* AsteriskAsteriskEqualsToken */; } return pos += 2, token = 43 /* AsteriskAsteriskToken */; @@ -13020,10 +12934,10 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } return token = 42 /* AsteriskToken */; case 43 /* plus */: - if (text.charCodeAt(pos + 1) === 43 /* plus */) { + if (charCodeUnchecked(pos + 1) === 43 /* plus */) { return pos += 2, token = 46 /* PlusPlusToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 65 /* PlusEqualsToken */; } pos++; @@ -13032,29 +12946,29 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 28 /* CommaToken */; case 45 /* minus */: - if (text.charCodeAt(pos + 1) === 45 /* minus */) { + if (charCodeUnchecked(pos + 1) === 45 /* minus */) { return pos += 2, token = 47 /* MinusMinusToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 66 /* MinusEqualsToken */; } pos++; return token = 41 /* MinusToken */; case 46 /* dot */: - if (isDigit(text.charCodeAt(pos + 1))) { + if (isDigit(charCodeUnchecked(pos + 1))) { scanNumber(); return token = 9 /* NumericLiteral */; } - if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) { + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && charCodeUnchecked(pos + 2) === 46 /* dot */) { return pos += 3, token = 26 /* DotDotDotToken */; } pos++; return token = 25 /* DotToken */; case 47 /* slash */: - if (text.charCodeAt(pos + 1) === 47 /* slash */) { + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; while (pos < end) { - if (isLineBreak(text.charCodeAt(pos))) { + if (isLineBreak(charCodeUnchecked(pos))) { break; } pos++; @@ -13071,14 +12985,14 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 2 /* SingleLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 42 /* asterisk */) { + if (charCodeUnchecked(pos + 1) === 42 /* asterisk */) { pos += 2; - const isJSDoc2 = text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */; + const isJSDoc2 = charCodeUnchecked(pos) === 42 /* asterisk */ && charCodeUnchecked(pos + 1) !== 47 /* slash */; let commentClosed = false; let lastLineStart = tokenStart; while (pos < end) { - const ch2 = text.charCodeAt(pos); - if (ch2 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) { + const ch2 = charCodeUnchecked(pos); + if (ch2 === 42 /* asterisk */ && charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; commentClosed = true; break; @@ -13105,13 +13019,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 3 /* MultiLineCommentTrivia */; } } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 69 /* SlashEqualsToken */; } pos++; return token = 44 /* SlashToken */; case 48 /* _0 */: - if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) { + if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 88 /* X */ || charCodeUnchecked(pos + 1) === 120 /* x */)) { pos += 2; tokenValue = scanMinimumNumberOfHexDigits( 1, @@ -13125,7 +13039,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = "0x" + tokenValue; tokenFlags |= 64 /* HexSpecifier */; return token = checkBigIntSuffix(); - } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) { + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 66 /* B */ || charCodeUnchecked(pos + 1) === 98 /* b */)) { pos += 2; tokenValue = scanBinaryOrOctalDigits( /* base */ @@ -13138,7 +13052,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenValue = "0b" + tokenValue; tokenFlags |= 128 /* BinarySpecifier */; return token = checkBigIntSuffix(); - } else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { + } else if (pos + 2 < end && (charCodeUnchecked(pos + 1) === 79 /* O */ || charCodeUnchecked(pos + 1) === 111 /* o */)) { pos += 2; tokenValue = scanBinaryOrOctalDigits( /* base */ @@ -13177,16 +13091,16 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 60 /* lessThan */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 60 /* lessThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 71 /* LessThanLessThanEqualsToken */; } return pos += 2, token = 48 /* LessThanLessThanToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 33 /* LessThanEqualsToken */; } - if (languageVariant === 1 /* JSX */ && text.charCodeAt(pos + 1) === 47 /* slash */ && text.charCodeAt(pos + 2) !== 42 /* asterisk */) { + if (languageVariant === 1 /* JSX */ && charCodeUnchecked(pos + 1) === 47 /* slash */ && charCodeUnchecked(pos + 2) !== 42 /* asterisk */) { return pos += 2, token = 31 /* LessThanSlashToken */; } pos++; @@ -13200,13 +13114,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 37 /* EqualsEqualsEqualsToken */; } return pos += 2, token = 35 /* EqualsEqualsToken */; } - if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { return pos += 2, token = 39 /* EqualsGreaterThanToken */; } pos++; @@ -13223,11 +13137,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 32 /* GreaterThanToken */; case 63 /* question */: - if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) { + if (charCodeUnchecked(pos + 1) === 46 /* dot */ && !isDigit(charCodeUnchecked(pos + 2))) { return pos += 2, token = 29 /* QuestionDotToken */; } - if (text.charCodeAt(pos + 1) === 63 /* question */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 63 /* question */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 78 /* QuestionQuestionEqualsToken */; } return pos += 2, token = 61 /* QuestionQuestionToken */; @@ -13241,7 +13155,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 24 /* CloseBracketToken */; case 94 /* caret */: - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 79 /* CaretEqualsToken */; } pos++; @@ -13258,13 +13172,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return token = 7 /* ConflictMarkerTrivia */; } } - if (text.charCodeAt(pos + 1) === 124 /* bar */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 124 /* bar */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 76 /* BarBarEqualsToken */; } return pos += 2, token = 57 /* BarBarToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 75 /* BarEqualsToken */; } pos++; @@ -13303,7 +13217,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan pos++; return token = 0 /* Unknown */; } - const charAfterHash = codePointAt(text, pos + 1); + const charAfterHash = codePointUnchecked(pos + 1); if (charAfterHash === 92 /* backslash */) { pos++; const extendedCookedChar2 = peekExtendedUnicodeEscape(); @@ -13373,7 +13287,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'."); pos = tokenStart = fullStartPos; tokenFlags = 0; - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); const identifierKind = scanIdentifier(ch, 99 /* ESNext */); if (identifierKind) { return token = identifierKind; @@ -13385,8 +13299,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let ch = startCharacter; if (isIdentifierStart(ch, languageVersion2)) { pos += charSize(ch); - while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion2)) - pos += charSize(ch); + while (pos < end && isIdentifierPart(ch = codePointUnchecked(pos), languageVersion2)) pos += charSize(ch); tokenValue = text.substring(tokenStart, pos); if (ch === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -13396,20 +13309,20 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function reScanGreaterToken() { if (token === 32 /* GreaterThanToken */) { - if (text.charCodeAt(pos) === 62 /* greaterThan */) { - if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) { - if (text.charCodeAt(pos + 2) === 61 /* equals */) { + if (charCodeUnchecked(pos) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 1) === 62 /* greaterThan */) { + if (charCodeUnchecked(pos + 2) === 61 /* equals */) { return pos += 3, token = 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */; } return pos += 2, token = 50 /* GreaterThanGreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos + 1) === 61 /* equals */) { + if (charCodeUnchecked(pos + 1) === 61 /* equals */) { return pos += 2, token = 72 /* GreaterThanGreaterThanEqualsToken */; } pos++; return token = 49 /* GreaterThanGreaterThanToken */; } - if (text.charCodeAt(pos) === 61 /* equals */) { + if (charCodeUnchecked(pos) === 61 /* equals */) { pos++; return token = 34 /* GreaterThanEqualsToken */; } @@ -13423,25 +13336,20 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function reScanSlashToken(reportErrors2) { if (token === 44 /* SlashToken */ || token === 69 /* SlashEqualsToken */) { - let p = tokenStart + 1; + const startOfRegExpBody = tokenStart + 1; + pos = startOfRegExpBody; let inEscape = false; + let namedCaptureGroups = false; let inCharacterClass = false; while (true) { - if (p >= end) { - tokenFlags |= 4 /* Unterminated */; - error2(Diagnostics.Unterminated_regular_expression_literal); - break; - } - const ch = text.charCodeAt(p); - if (isLineBreak(ch)) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || isLineBreak(ch)) { tokenFlags |= 4 /* Unterminated */; - error2(Diagnostics.Unterminated_regular_expression_literal); break; } if (inEscape) { inEscape = false; } else if (ch === 47 /* slash */ && !inCharacterClass) { - p++; break; } else if (ch === 91 /* openBracket */) { inCharacterClass = true; @@ -13449,871 +13357,918 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan inEscape = true; } else if (ch === 93 /* closeBracket */) { inCharacterClass = false; + } else if (!inCharacterClass && ch === 40 /* openParen */ && charCodeChecked(pos + 1) === 63 /* question */ && charCodeChecked(pos + 2) === 60 /* lessThan */ && charCodeChecked(pos + 3) !== 61 /* equals */ && charCodeChecked(pos + 3) !== 33 /* exclamation */) { + namedCaptureGroups = true; } - p++; + pos++; } - const isUnterminated = !!(tokenFlags & 4 /* Unterminated */); - const endOfBody = p - (isUnterminated ? 0 : 1); - let regExpFlags = 0 /* None */; - while (p < end) { - const ch = text.charCodeAt(p); - if (!isIdentifierPart(ch, languageVersion)) { - break; + const endOfRegExpBody = pos; + if (tokenFlags & 4 /* Unterminated */) { + pos = startOfRegExpBody; + inEscape = false; + let characterClassDepth = 0; + let inDecimalQuantifier = false; + let groupDepth = 0; + while (pos < endOfRegExpBody) { + const ch = charCodeUnchecked(pos); + if (inEscape) { + inEscape = false; + } else if (ch === 92 /* backslash */) { + inEscape = true; + } else if (ch === 91 /* openBracket */) { + characterClassDepth++; + } else if (ch === 93 /* closeBracket */ && characterClassDepth) { + characterClassDepth--; + } else if (!characterClassDepth) { + if (ch === 123 /* openBrace */) { + inDecimalQuantifier = true; + } else if (ch === 125 /* closeBrace */ && inDecimalQuantifier) { + inDecimalQuantifier = false; + } else if (!inDecimalQuantifier) { + if (ch === 40 /* openParen */) { + groupDepth++; + } else if (ch === 41 /* closeParen */ && groupDepth) { + groupDepth--; + } else if (ch === 41 /* closeParen */ || ch === 93 /* closeBracket */ || ch === 125 /* closeBrace */) { + break; + } + } + } + pos++; } - if (reportErrors2) { - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); - if (flag === void 0) { - error2(Diagnostics.Unknown_regular_expression_flag, p, 1); - } else if (regExpFlags & flag) { - error2(Diagnostics.Duplicate_regular_expression_flag, p, 1); - } else if (((regExpFlags | flag) & 96 /* UnicodeMode */) === 96 /* UnicodeMode */) { - error2(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, p, 1); - } else { - regExpFlags |= flag; - const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); - if (languageVersion < availableFrom) { - error2(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, p, 1, getNameOfScriptTarget(availableFrom)); + while (isWhiteSpaceLike(charCodeChecked(pos - 1)) || charCodeChecked(pos - 1) === 59 /* semicolon */) pos--; + error2(Diagnostics.Unterminated_regular_expression_literal, tokenStart, pos - tokenStart); + } else { + pos++; + let regExpFlags = 0 /* None */; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + if (reportErrors2) { + const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + if (flag === void 0) { + error2(Diagnostics.Unknown_regular_expression_flag, pos, 1); + } else if (regExpFlags & flag) { + error2(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + } else if (((regExpFlags | flag) & 96 /* AnyUnicodeMode */) === 96 /* AnyUnicodeMode */) { + error2(Diagnostics.The_Unicode_u_flag_and_the_Unicode_Sets_v_flag_cannot_be_set_simultaneously, pos, 1); + } else { + regExpFlags |= flag; + checkRegularExpressionFlagAvailable(flag, pos); } } + pos++; } - p++; - } - if (reportErrors2) { - pos = tokenStart + 1; - const saveTokenPos = tokenStart; - const saveTokenFlags = tokenFlags; - scanRegularExpressionWorker( - text, - endOfBody, - regExpFlags, - isUnterminated, - /*annexB*/ - true - ); - if (!isUnterminated) { - pos = p; + if (reportErrors2) { + scanRange(startOfRegExpBody, endOfRegExpBody - startOfRegExpBody, () => { + scanRegularExpressionWorker( + regExpFlags, + /*annexB*/ + true, + namedCaptureGroups + ); + }); } - tokenStart = saveTokenPos; - tokenFlags = saveTokenFlags; - } else { - pos = p; } tokenValue = text.substring(tokenStart, pos); token = 14 /* RegularExpressionLiteral */; } return token; - function scanRegularExpressionWorker(text2, end2, regExpFlags, isUnterminated, annexB) { - const unicodeSetsMode = !!(regExpFlags & 64 /* UnicodeSets */); - const unicodeMode = !!(regExpFlags & 96 /* UnicodeMode */); - if (unicodeMode) { - annexB = false; - } - let mayContainStrings = false; - let numberOfCapturingGroups = 0; - const groupSpecifiers = /* @__PURE__ */ new Set(); - const groupNameReferences = []; - const decimalEscapes = []; - const namedCapturingGroups = []; - function scanDisjunction(isInGroup) { - while (true) { - namedCapturingGroups.push(/* @__PURE__ */ new Set()); - scanAlternative(isInGroup); - namedCapturingGroups.pop(); - if (text2.charCodeAt(pos) !== 124 /* bar */) { - return; - } - pos++; + } + function scanRegularExpressionWorker(regExpFlags, annexB, namedCaptureGroups) { + var unicodeSetsMode = !!(regExpFlags & 64 /* UnicodeSets */); + var anyUnicodeMode = !!(regExpFlags & 96 /* AnyUnicodeMode */); + var anyUnicodeModeOrNonAnnexB = anyUnicodeMode || !annexB; + var mayContainStrings = false; + var numberOfCapturingGroups = 0; + var groupSpecifiers; + var groupNameReferences; + var decimalEscapes; + var namedCapturingGroupsScopeStack = []; + var topNamedCapturingGroupsScope; + function scanDisjunction(isInGroup) { + while (true) { + namedCapturingGroupsScopeStack.push(topNamedCapturingGroupsScope); + topNamedCapturingGroupsScope = void 0; + scanAlternative(isInGroup); + topNamedCapturingGroupsScope = namedCapturingGroupsScopeStack.pop(); + if (charCodeChecked(pos) !== 124 /* bar */) { + return; } + pos++; } - function scanAlternative(isInGroup) { - let isPreviousTermQuantifiable = false; - while (pos < end2) { - const start2 = pos; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 94 /* caret */: - case 36 /* $ */: - pos++; - isPreviousTermQuantifiable = false; - break; - case 92 /* backslash */: + } + function scanAlternative(isInGroup) { + let isPreviousTermQuantifiable = false; + while (true) { + const start2 = pos; + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 94 /* caret */: + case 36 /* $ */: + pos++; + isPreviousTermQuantifiable = false; + break; + case 92 /* backslash */: + pos++; + switch (charCodeChecked(pos)) { + case 98 /* b */: + case 66 /* B */: + pos++; + isPreviousTermQuantifiable = false; + break; + default: + scanAtomEscape(); + isPreviousTermQuantifiable = true; + break; + } + break; + case 40 /* openParen */: + pos++; + if (charCodeChecked(pos) === 63 /* question */) { pos++; - switch (text2.charCodeAt(pos)) { - case 98 /* b */: - case 66 /* B */: + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: pos++; - isPreviousTermQuantifiable = false; + isPreviousTermQuantifiable = !anyUnicodeModeOrNonAnnexB; break; - default: - scanAtomEscape(); - isPreviousTermQuantifiable = true; - break; - } - break; - case 40 /* openParen */: - pos++; - if (text2.charCodeAt(pos) === 63 /* question */) { - pos++; - switch (text2.charCodeAt(pos)) { - case 61 /* equals */: - case 33 /* exclamation */: - pos++; - isPreviousTermQuantifiable = annexB; - break; - case 60 /* lessThan */: - const groupNameStart = pos; - pos++; - switch (text2.charCodeAt(pos)) { - case 61 /* equals */: - case 33 /* exclamation */: - pos++; - isPreviousTermQuantifiable = false; - break; - default: - scanGroupName( - /*isReference*/ - false - ); - scanExpectedChar(62 /* greaterThan */); - if (languageVersion < 5 /* ES2018 */) { - error2(Diagnostics.Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later, groupNameStart, pos - groupNameStart); - } - numberOfCapturingGroups++; - isPreviousTermQuantifiable = true; - break; - } - break; - default: - const start3 = pos; - const setFlags = scanPatternModifiers(0 /* None */); - if (text2.charCodeAt(pos) === 45 /* minus */) { + case 60 /* lessThan */: + const groupNameStart = pos; + pos++; + switch (charCodeChecked(pos)) { + case 61 /* equals */: + case 33 /* exclamation */: pos++; - scanPatternModifiers(setFlags); - if (pos === start3 + 1) { - error2(Diagnostics.Subpattern_flags_must_be_present_when_there_is_a_minus_sign, start3, pos - start3); + isPreviousTermQuantifiable = false; + break; + default: + scanGroupName( + /*isReference*/ + false + ); + scanExpectedChar(62 /* greaterThan */); + if (languageVersion < 5 /* ES2018 */) { + error2(Diagnostics.Named_capturing_groups_are_only_available_when_targeting_ES2018_or_later, groupNameStart, pos - groupNameStart); } + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + break; + } + break; + default: + const start3 = pos; + const setFlags = scanPatternModifiers(0 /* None */); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + scanPatternModifiers(setFlags); + if (pos === start3 + 1) { + error2(Diagnostics.Subpattern_flags_must_be_present_when_there_is_a_minus_sign, start3, pos - start3); } - scanExpectedChar(58 /* colon */); - isPreviousTermQuantifiable = true; - break; - } - } else { - numberOfCapturingGroups++; - isPreviousTermQuantifiable = true; + } + scanExpectedChar(58 /* colon */); + isPreviousTermQuantifiable = true; + break; } - scanDisjunction( - /*isInGroup*/ - true - ); - scanExpectedChar(41 /* closeParen */); + } else { + numberOfCapturingGroups++; + isPreviousTermQuantifiable = true; + } + scanDisjunction( + /*isInGroup*/ + true + ); + scanExpectedChar(41 /* closeParen */); + break; + case 123 /* openBrace */: + pos++; + const digitsStart = pos; + scanDigits(); + const min2 = tokenValue; + if (!anyUnicodeModeOrNonAnnexB && !min2) { + isPreviousTermQuantifiable = true; break; - case 123 /* openBrace */: + } + if (charCodeChecked(pos) === 44 /* comma */) { pos++; - const digitsStart = pos; scanDigits(); - const min2 = tokenValue; - if (text2.charCodeAt(pos) === 44 /* comma */) { - pos++; - scanDigits(); - const max = tokenValue; - if (!min2) { - if (max || text2.charCodeAt(pos) === 125 /* closeBrace */) { - error2(Diagnostics.Incomplete_quantifier_Digit_expected, digitsStart, 0); - } else { - if (unicodeMode) { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); - } - isPreviousTermQuantifiable = true; - break; - } - } - if (max && Number.parseInt(min2) > Number.parseInt(max)) { - error2(Diagnostics.Numbers_out_of_order_in_quantifier, digitsStart, pos - digitsStart); - } - } else if (!min2) { - if (unicodeMode) { + const max = tokenValue; + if (!min2) { + if (max || charCodeChecked(pos) === 125 /* closeBrace */) { + error2(Diagnostics.Incomplete_quantifier_Digit_expected, digitsStart, 0); + } else { error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); + isPreviousTermQuantifiable = true; + break; } - isPreviousTermQuantifiable = true; - break; + } else if (max && Number.parseInt(min2) > Number.parseInt(max) && (anyUnicodeModeOrNonAnnexB || charCodeChecked(pos) === 125 /* closeBrace */)) { + error2(Diagnostics.Numbers_out_of_order_in_quantifier, digitsStart, pos - digitsStart); } - scanExpectedChar(125 /* closeBrace */); - pos--; - case 42 /* asterisk */: - case 43 /* plus */: - case 63 /* question */: - pos++; - if (text2.charCodeAt(pos) === 63 /* question */) { - pos++; + } else if (!min2) { + if (anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, start2, 1, String.fromCharCode(ch)); } - if (!isPreviousTermQuantifiable) { - error2(Diagnostics.There_is_nothing_available_for_repetition, start2, pos - start2); - } - isPreviousTermQuantifiable = false; - break; - case 46 /* dot */: - pos++; isPreviousTermQuantifiable = true; break; - case 91 /* openBracket */: - pos++; - if (unicodeSetsMode) { - scanClassSetExpression(); + } + if (charCodeChecked(pos) !== 125 /* closeBrace */) { + if (anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics._0_expected, pos, 0, String.fromCharCode(125 /* closeBrace */)); + pos--; } else { - scanClassRanges(); - } - scanExpectedChar(93 /* closeBracket */); - isPreviousTermQuantifiable = true; - break; - case 41 /* closeParen */: - if (isInGroup) { - return; - } - case 93 /* closeBracket */: - case 125 /* closeBrace */: - if (isUnterminated && !isInGroup) { - return; - } - if (unicodeMode || ch === 41 /* closeParen */) { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + isPreviousTermQuantifiable = true; + break; } - pos++; - isPreviousTermQuantifiable = true; - break; - case 47 /* slash */: - case 124 /* bar */: - return; - default: - scanSourceCharacter(); - isPreviousTermQuantifiable = true; - break; - } - } - } - function scanPatternModifiers(currFlags) { - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (!isIdentifierPart(ch, languageVersion)) { - break; - } - const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); - if (flag === void 0) { - error2(Diagnostics.Unknown_regular_expression_flag, pos, 1); - } else if (currFlags & flag) { - error2(Diagnostics.Duplicate_regular_expression_flag, pos, 1); - } else if (!(flag & 28 /* Modifiers */)) { - error2(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, 1); - } else { - currFlags |= flag; - const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); - if (languageVersion < availableFrom) { - error2(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos, 1, getNameOfScriptTarget(availableFrom)); } - } - pos++; - } - return currFlags; - } - function scanAtomEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - switch (text2.charCodeAt(pos)) { - case 107 /* k */: + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: pos++; - if (text2.charCodeAt(pos) === 60 /* lessThan */) { + if (charCodeChecked(pos) === 63 /* question */) { pos++; - scanGroupName( - /*isReference*/ - true - ); - scanExpectedChar(62 /* greaterThan */); - } else if (unicodeMode) { - error2(Diagnostics.k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets, pos - 2, 2); } - break; - case 113 /* q */: - if (unicodeSetsMode) { - pos++; - error2(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); - break; + if (!isPreviousTermQuantifiable) { + error2(Diagnostics.There_is_nothing_available_for_repetition, start2, pos - start2); } - default: - Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( - /*atomEscape*/ - true - )); + isPreviousTermQuantifiable = false; break; - } - } - function scanDecimalEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - const ch = text2.charCodeAt(pos); - if (ch >= 49 /* _1 */ && ch <= 57 /* _9 */) { - const start2 = pos; - scanDigits(); - decimalEscapes.push({ pos: start2, end: pos, value: +tokenValue }); - return true; - } - return false; - } - function scanCharacterEscape(atomEscape) { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - let ch = text2.charCodeAt(pos); - switch (ch) { - case 99 /* c */: + case 46 /* dot */: pos++; - ch = text2.charCodeAt(pos); - if (isASCIILetter(ch)) { - pos++; - return String.fromCharCode(ch & 31); - } - if (unicodeMode) { - error2(Diagnostics.c_must_be_followed_by_an_ASCII_letter, pos - 2, 2); - } else if (atomEscape && annexB) { - pos--; - return "\\"; + isPreviousTermQuantifiable = true; + break; + case 91 /* openBracket */: + pos++; + if (unicodeSetsMode) { + scanClassSetExpression(); + } else { + scanClassRanges(); } - return String.fromCharCode(ch); - case 94 /* caret */: - case 36 /* $ */: - case 47 /* slash */: - case 92 /* backslash */: - case 46 /* dot */: - case 42 /* asterisk */: - case 43 /* plus */: - case 63 /* question */: - case 40 /* openParen */: + scanExpectedChar(93 /* closeBracket */); + isPreviousTermQuantifiable = true; + break; case 41 /* closeParen */: - case 91 /* openBracket */: + if (isInGroup) { + return; + } case 93 /* closeBracket */: - case 123 /* openBrace */: case 125 /* closeBrace */: - case 124 /* bar */: + if (anyUnicodeModeOrNonAnnexB || ch === 41 /* closeParen */) { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } pos++; - return String.fromCharCode(ch); + isPreviousTermQuantifiable = true; + break; + case 47 /* slash */: + case 124 /* bar */: + return; default: - if (pos >= end2) { - error2(Diagnostics.Undetermined_character_escape, pos - 1, 1, ch); - return "\\"; - } - pos--; - return scanEscapeSequence( - /*shouldEmitInvalidEscapeError*/ - unicodeMode, - /*isRegularExpression*/ - annexB ? "annex-b" : true - ); + scanSourceCharacter(); + isPreviousTermQuantifiable = true; + break; } } - function scanGroupName(isReference) { - Debug.assertEqual(text2.charCodeAt(pos - 1), 60 /* lessThan */); - tokenStart = pos; - scanIdentifier(codePointAt(text2, pos), languageVersion); - if (pos === tokenStart) { - error2(Diagnostics.Expected_a_capturing_group_name); - } else if (isReference) { - groupNameReferences.push({ pos: tokenStart, end: pos, name: tokenValue }); - } else if (namedCapturingGroups.some((group2) => group2.has(tokenValue))) { - error2(Diagnostics.Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other, tokenStart, pos - tokenStart); + } + function scanPatternModifiers(currFlags) { + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isIdentifierPart(ch, languageVersion)) { + break; + } + const flag = characterToRegularExpressionFlag(String.fromCharCode(ch)); + if (flag === void 0) { + error2(Diagnostics.Unknown_regular_expression_flag, pos, 1); + } else if (currFlags & flag) { + error2(Diagnostics.Duplicate_regular_expression_flag, pos, 1); + } else if (!(flag & 28 /* Modifiers */)) { + error2(Diagnostics.This_regular_expression_flag_cannot_be_toggled_within_a_subpattern, pos, 1); } else { - last(namedCapturingGroups).add(tokenValue); - groupSpecifiers.add(tokenValue); + currFlags |= flag; + checkRegularExpressionFlagAvailable(flag, pos); } + pos++; + } + return currFlags; + } + function scanAtomEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + switch (charCodeChecked(pos)) { + case 107 /* k */: + pos++; + if (charCodeChecked(pos) === 60 /* lessThan */) { + pos++; + scanGroupName( + /*isReference*/ + true + ); + scanExpectedChar(62 /* greaterThan */); + } else if (anyUnicodeModeOrNonAnnexB || namedCaptureGroups) { + error2(Diagnostics.k_must_be_followed_by_a_capturing_group_name_enclosed_in_angle_brackets, pos - 2, 2); + } + break; + case 113 /* q */: + if (unicodeSetsMode) { + pos++; + error2(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); + break; + } + default: + Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( + /*atomEscape*/ + true + )); + break; } - function isClassContentExit(ch) { - return ch === 93 /* closeBracket */ || pos >= end2; + } + function scanDecimalEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + const ch = charCodeChecked(pos); + if (ch >= 49 /* _1 */ && ch <= 57 /* _9 */) { + const start2 = pos; + scanDigits(); + decimalEscapes = append(decimalEscapes, { pos: start2, end: pos, value: +tokenValue }); + return true; } - function scanClassRanges() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 91 /* openBracket */); - if (text2.charCodeAt(pos) === 94 /* caret */) { + return false; + } + function scanCharacterEscape(atomEscape) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + error2(Diagnostics.Undetermined_character_escape, pos - 1, 1); + return "\\"; + case 99 /* c */: + pos++; + ch = charCodeChecked(pos); + if (isASCIILetter(ch)) { + pos++; + return String.fromCharCode(ch & 31); + } + if (anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics.c_must_be_followed_by_an_ASCII_letter, pos - 2, 2); + } else if (atomEscape) { + pos--; + return "\\"; + } + return String.fromCharCode(ch); + case 94 /* caret */: + case 36 /* $ */: + case 47 /* slash */: + case 92 /* backslash */: + case 46 /* dot */: + case 42 /* asterisk */: + case 43 /* plus */: + case 63 /* question */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 124 /* bar */: pos++; + return String.fromCharCode(ch); + default: + pos--; + return scanEscapeSequence( + 4 /* RegularExpression */ | (annexB ? 8 /* AnnexB */ : 0) | (anyUnicodeMode ? 16 /* AnyUnicodeMode */ : 0) | (atomEscape ? 32 /* AtomEscape */ : 0) + ); + } + } + function scanGroupName(isReference) { + Debug.assertEqual(charCodeUnchecked(pos - 1), 60 /* lessThan */); + tokenStart = pos; + scanIdentifier(codePointChecked(pos), languageVersion); + if (pos === tokenStart) { + error2(Diagnostics.Expected_a_capturing_group_name); + } else if (isReference) { + groupNameReferences = append(groupNameReferences, { pos: tokenStart, end: pos, name: tokenValue }); + } else if ((topNamedCapturingGroupsScope == null ? void 0 : topNamedCapturingGroupsScope.has(tokenValue)) || namedCapturingGroupsScopeStack.some((group2) => group2 == null ? void 0 : group2.has(tokenValue))) { + error2(Diagnostics.Named_capturing_groups_with_the_same_name_must_be_mutually_exclusive_to_each_other, tokenStart, pos - tokenStart); + } else { + topNamedCapturingGroupsScope ?? (topNamedCapturingGroupsScope = /* @__PURE__ */ new Set()); + topNamedCapturingGroupsScope.add(tokenValue); + groupSpecifiers ?? (groupSpecifiers = /* @__PURE__ */ new Set()); + groupSpecifiers.add(tokenValue); + } + } + function isClassContentExit(ch) { + return ch === 93 /* closeBracket */ || ch === -1 /* EOF */ || pos >= end; + } + function scanClassRanges() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + } + while (true) { + const ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; } - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { + const minStart = pos; + const minCharacter = scanClassAtom(); + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + const ch2 = charCodeChecked(pos); + if (isClassContentExit(ch2)) { return; } - const minStart = pos; - const minCharacter = scanClassAtom(); - if (text2.charCodeAt(pos) === 45 /* minus */) { - pos++; - const ch2 = text2.charCodeAt(pos); - if (isClassContentExit(ch2)) { - return; + if (!minCharacter && anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, minStart, pos - 1 - minStart); + } + const maxStart = pos; + const maxCharacter = scanClassAtom(); + if (!maxCharacter && anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, maxStart, pos - maxStart); + continue; + } + if (!minCharacter) { + continue; + } + const minCharacterValue = codePointAt(minCharacter, 0); + const maxCharacterValue = codePointAt(maxCharacter, 0); + if (minCharacter.length === charSize(minCharacterValue) && maxCharacter.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error2(Diagnostics.Range_out_of_order_in_character_class, minStart, pos - minStart); + } + } + } + } + function scanClassSetExpression() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 91 /* openBracket */); + let isCharacterComplement = false; + if (charCodeChecked(pos) === 94 /* caret */) { + pos++; + isCharacterComplement = true; + } + let expressionMayContainStrings = false; + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + return; + } + let start2 = pos; + let operand; + switch (text.slice(pos, pos + 2)) { + case "--": + case "&&": + error2(Diagnostics.Expected_a_class_set_operand); + mayContainStrings = false; + break; + default: + operand = scanClassSetOperand(); + break; + } + switch (charCodeChecked(pos)) { + case 45 /* minus */: + if (charCodeChecked(pos + 1) === 45 /* minus */) { + if (isCharacterComplement && mayContainStrings) { + error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); } - if (!minCharacter && !annexB) { - error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, minStart, pos - 1 - minStart); + expressionMayContainStrings = mayContainStrings; + scanClassSetSubExpression(3 /* ClassSubtraction */); + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } + break; + case 38 /* ampersand */: + if (charCodeChecked(pos + 1) === 38 /* ampersand */) { + scanClassSetSubExpression(2 /* ClassIntersection */); + if (isCharacterComplement && mayContainStrings) { + error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); } - const maxStart = pos; - const maxCharacter = scanClassAtom(); - if (!maxCharacter && !annexB) { - error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, maxStart, pos - maxStart); - continue; + expressionMayContainStrings = mayContainStrings; + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; + } else { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + } + break; + default: + if (isCharacterComplement && mayContainStrings) { + error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + } + expressionMayContainStrings = mayContainStrings; + break; + } + while (true) { + ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + break; + } + switch (ch) { + case 45 /* minus */: + pos++; + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + return; } - if (!minCharacter) { + if (ch === 45 /* minus */) { + pos++; + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + start2 = pos - 2; + operand = text.slice(start2, pos); continue; + } else { + if (!operand) { + error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, start2, pos - 1 - start2); + } + const secondStart = pos; + const secondOperand = scanClassSetOperand(); + if (isCharacterComplement && mayContainStrings) { + error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, secondStart, pos - secondStart); + } + expressionMayContainStrings || (expressionMayContainStrings = mayContainStrings); + if (!secondOperand) { + error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, secondStart, pos - secondStart); + break; + } + if (!operand) { + break; + } + const minCharacterValue = codePointAt(operand, 0); + const maxCharacterValue = codePointAt(secondOperand, 0); + if (operand.length === charSize(minCharacterValue) && secondOperand.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { + error2(Diagnostics.Range_out_of_order_in_character_class, start2, pos - start2); + } } - const minCharacterValue = codePointAt(minCharacter, 0); - const maxCharacterValue = codePointAt(maxCharacter, 0); - if (minCharacter.length === charSize(minCharacterValue) && maxCharacter.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { - error2(Diagnostics.Range_out_of_order_in_character_class, minStart, pos - minStart); + break; + case 38 /* ampersand */: + start2 = pos; + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + if (charCodeChecked(pos) === 38 /* ampersand */) { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; + } + } else { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); } - } - } - } - function scanClassSetExpression() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 91 /* openBracket */); - let isCharacterComplement = false; - if (text2.charCodeAt(pos) === 94 /* caret */) { - pos++; - isCharacterComplement = true; + operand = text.slice(start2, pos); + continue; } - let expressionMayContainStrings = false; - let ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - return; + if (isClassContentExit(charCodeChecked(pos))) { + break; } - let start2 = pos; - let oprand; - switch (text2.slice(pos, pos + 2)) { + start2 = pos; + switch (text.slice(pos, pos + 2)) { case "--": case "&&": - error2(Diagnostics.Expected_a_class_set_oprand); - mayContainStrings = false; + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); + pos += 2; + operand = text.slice(start2, pos); break; default: - oprand = scanClassSetOprand(); + operand = scanClassSetOperand(); break; } - switch (text2.charCodeAt(pos)) { + } + mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + } + function scanClassSetSubExpression(expressionType) { + let expressionMayContainStrings = mayContainStrings; + while (true) { + let ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + break; + } + switch (ch) { case 45 /* minus */: - if (text2.charCodeAt(pos + 1) === 45 /* minus */) { - if (isCharacterComplement && mayContainStrings) { - error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + pos++; + if (charCodeChecked(pos) === 45 /* minus */) { + pos++; + if (expressionType !== 3 /* ClassSubtraction */) { + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); } - expressionMayContainStrings = mayContainStrings; - scanClassSetSubExpression(3 /* ClassSubtraction */); - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; + } else { + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 1, 1); } break; case 38 /* ampersand */: - if (text2.charCodeAt(pos + 1) === 38 /* ampersand */) { - scanClassSetSubExpression(2 /* ClassIntersection */); - if (isCharacterComplement && mayContainStrings) { - error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + pos++; + if (charCodeChecked(pos) === 38 /* ampersand */) { + pos++; + if (expressionType !== 2 /* ClassIntersection */) { + error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); + } + if (charCodeChecked(pos) === 38 /* ampersand */) { + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + pos++; } - expressionMayContainStrings = mayContainStrings; - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; } else { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); } break; default: - if (isCharacterComplement && mayContainStrings) { - error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, start2, pos - start2); + switch (expressionType) { + case 3 /* ClassSubtraction */: + error2(Diagnostics._0_expected, pos, 0, "--"); + break; + case 2 /* ClassIntersection */: + error2(Diagnostics._0_expected, pos, 0, "&&"); + break; + default: + break; } - expressionMayContainStrings = mayContainStrings; break; } - while (pos < end2) { - ch = text2.charCodeAt(pos); - switch (ch) { - case 45 /* minus */: - pos++; - ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; - return; - } - if (ch === 45 /* minus */) { - pos++; - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - start2 = pos - 2; - oprand = text2.slice(start2, pos); - continue; - } else { - if (!oprand) { - error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, start2, pos - 1 - start2); - } - const secondStart = pos; - const secondOprand = scanClassSetOprand(); - if (isCharacterComplement && mayContainStrings) { - error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, secondStart, pos - secondStart); - } - expressionMayContainStrings || (expressionMayContainStrings = mayContainStrings); - if (!secondOprand) { - error2(Diagnostics.A_character_class_range_must_not_be_bounded_by_another_character_class, secondStart, pos - secondStart); - break; - } - if (!oprand) { - break; - } - const minCharacterValue = codePointAt(oprand, 0); - const maxCharacterValue = codePointAt(secondOprand, 0); - if (oprand.length === charSize(minCharacterValue) && secondOprand.length === charSize(maxCharacterValue) && minCharacterValue > maxCharacterValue) { - error2(Diagnostics.Range_out_of_order_in_character_class, start2, pos - start2); - } - } - break; - case 38 /* ampersand */: - start2 = pos; - pos++; - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - pos++; - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); - pos++; - } - } else { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); - } - oprand = text2.slice(start2, pos); - continue; - } - if (isClassContentExit(text2.charCodeAt(pos))) { - break; - } - start2 = pos; - switch (text2.slice(pos, pos + 2)) { - case "--": - case "&&": - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); - pos += 2; - oprand = text2.slice(start2, pos); - break; - default: - oprand = scanClassSetOprand(); - break; - } + ch = charCodeChecked(pos); + if (isClassContentExit(ch)) { + error2(Diagnostics.Expected_a_class_set_operand); + break; } - mayContainStrings = !isCharacterComplement && expressionMayContainStrings; + scanClassSetOperand(); + expressionMayContainStrings && (expressionMayContainStrings = mayContainStrings); } - function scanClassSetSubExpression(expressionType) { - let expressionMayContainStrings = mayContainStrings; - while (pos < end2) { - let ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - break; - } - switch (ch) { - case 45 /* minus */: - pos++; - if (text2.charCodeAt(pos) === 45 /* minus */) { - pos++; - if (expressionType !== 3 /* ClassSubtraction */) { - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - } - } else { - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 1, 1); - } - break; - case 38 /* ampersand */: + mayContainStrings = expressionMayContainStrings; + } + function scanClassSetOperand() { + mayContainStrings = false; + switch (charCodeChecked(pos)) { + case -1 /* EOF */: + return ""; + case 91 /* openBracket */: + pos++; + scanClassSetExpression(); + scanExpectedChar(93 /* closeBracket */); + return ""; + case 92 /* backslash */: + pos++; + if (scanCharacterClassEscape()) { + return ""; + } else if (charCodeChecked(pos) === 113 /* q */) { + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { pos++; - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - pos++; - if (expressionType !== 2 /* ClassIntersection */) { - error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos - 2, 2); - } - if (text2.charCodeAt(pos) === 38 /* ampersand */) { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); - pos++; - } - } else { - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos - 1, 1, String.fromCharCode(ch)); - } - break; - default: - switch (expressionType) { - case 3 /* ClassSubtraction */: - error2(Diagnostics._0_expected, pos, 0, "--"); - break; - case 2 /* ClassIntersection */: - error2(Diagnostics._0_expected, pos, 0, "&&"); - break; - default: - break; - } - break; + scanClassStringDisjunctionContents(); + scanExpectedChar(125 /* closeBrace */); + return ""; + } else { + error2(Diagnostics.q_must_be_followed_by_string_alternatives_enclosed_in_braces, pos - 2, 2); + return "q"; + } } - ch = text2.charCodeAt(pos); - if (isClassContentExit(ch)) { - error2(Diagnostics.Expected_a_class_set_oprand); + pos--; + default: + return scanClassSetCharacter(); + } + } + function scanClassStringDisjunctionContents() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 123 /* openBrace */); + let characterCount = 0; + while (true) { + const ch = charCodeChecked(pos); + switch (ch) { + case -1 /* EOF */: + return; + case 125 /* closeBrace */: + if (characterCount !== 1) { + mayContainStrings = true; + } + return; + case 124 /* bar */: + if (characterCount !== 1) { + mayContainStrings = true; + } + pos++; + start = pos; + characterCount = 0; + break; + default: + scanClassSetCharacter(); + characterCount++; break; - } - scanClassSetOprand(); - expressionMayContainStrings && (expressionMayContainStrings = mayContainStrings); } - mayContainStrings = expressionMayContainStrings; } - function scanClassSetOprand() { - mayContainStrings = false; - switch (text2.charCodeAt(pos)) { - case 91 /* openBracket */: + } + function scanClassSetCharacter() { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */) { + return ""; + } + if (ch === 92 /* backslash */) { + pos++; + const ch2 = charCodeChecked(pos); + switch (ch2) { + case 98 /* b */: pos++; - scanClassSetExpression(); - scanExpectedChar(93 /* closeBracket */); - return ""; - case 92 /* backslash */: + return "\b"; + case 38 /* ampersand */: + case 45 /* minus */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 44 /* comma */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: pos++; - if (scanCharacterClassEscape()) { - return ""; - } else if (text2.charCodeAt(pos) === 113 /* q */) { - pos++; - if (text2.charCodeAt(pos) === 123 /* openBrace */) { - pos++; - scanClassStringDisjunctionContents(); - scanExpectedChar(125 /* closeBrace */); - return ""; - } else { - error2(Diagnostics.q_must_be_followed_by_string_alternatives_enclosed_in_braces, pos - 2, 2); - return "q"; - } - } - pos--; + return String.fromCharCode(ch2); default: - return scanClassSetCharacter(); - } - } - function scanClassStringDisjunctionContents() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 123 /* openBrace */); - let characterCount = 0; - while (pos < end2) { - const ch = text2.charCodeAt(pos); - switch (ch) { - case 125 /* closeBrace */: - if (characterCount !== 1) { - mayContainStrings = true; - } - return; - case 124 /* bar */: - if (characterCount !== 1) { - mayContainStrings = true; - } - pos++; - start = pos; - characterCount = 0; - break; - default: - scanClassSetCharacter(); - characterCount++; - break; - } + return scanCharacterEscape( + /*atomEscape*/ + false + ); + } + } else if (ch === charCodeChecked(pos + 1)) { + switch (ch) { + case 38 /* ampersand */: + case 33 /* exclamation */: + case 35 /* hash */: + case 37 /* percent */: + case 42 /* asterisk */: + case 43 /* plus */: + case 44 /* comma */: + case 46 /* dot */: + case 58 /* colon */: + case 59 /* semicolon */: + case 60 /* lessThan */: + case 61 /* equals */: + case 62 /* greaterThan */: + case 63 /* question */: + case 64 /* at */: + case 96 /* backtick */: + case 126 /* tilde */: + error2(Diagnostics.A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash, pos, 2); + pos += 2; + return text.substring(pos - 2, pos); } } - function scanClassSetCharacter() { - const ch = text2.charCodeAt(pos); - if (ch === 92 /* backslash */) { + switch (ch) { + case 47 /* slash */: + case 40 /* openParen */: + case 41 /* closeParen */: + case 91 /* openBracket */: + case 93 /* closeBracket */: + case 123 /* openBrace */: + case 125 /* closeBrace */: + case 45 /* minus */: + case 124 /* bar */: + error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); pos++; - const ch2 = text2.charCodeAt(pos); - switch (ch2) { - case 98 /* b */: - pos++; - return "\b"; - case 38 /* ampersand */: - case 45 /* minus */: - case 33 /* exclamation */: - case 35 /* hash */: - case 37 /* percent */: - case 44 /* comma */: - case 58 /* colon */: - case 59 /* semicolon */: - case 60 /* lessThan */: - case 61 /* equals */: - case 62 /* greaterThan */: - case 64 /* at */: - case 96 /* backtick */: - case 126 /* tilde */: - pos++; - return String.fromCharCode(ch2); - default: - return scanCharacterEscape( - /*atomEscape*/ - false - ); - } - } else if (ch === text2.charCodeAt(pos + 1)) { - switch (ch) { - case 38 /* ampersand */: - case 33 /* exclamation */: - case 35 /* hash */: - case 37 /* percent */: - case 42 /* asterisk */: - case 43 /* plus */: - case 44 /* comma */: - case 46 /* dot */: - case 58 /* colon */: - case 59 /* semicolon */: - case 60 /* lessThan */: - case 61 /* equals */: - case 62 /* greaterThan */: - case 63 /* question */: - case 64 /* at */: - case 96 /* backtick */: - case 126 /* tilde */: - error2(Diagnostics.A_character_class_must_not_contain_a_reserved_double_punctuator_Did_you_mean_to_escape_it_with_backslash, pos, 2); - pos += 2; - return text2.substring(pos - 2, pos); - } - } + return String.fromCharCode(ch); + } + return scanSourceCharacter(); + } + function scanClassAtom() { + if (charCodeChecked(pos) === 92 /* backslash */) { + pos++; + const ch = charCodeChecked(pos); switch (ch) { - case 47 /* slash */: - case 40 /* openParen */: - case 41 /* closeParen */: - case 91 /* openBracket */: - case 93 /* closeBracket */: - case 123 /* openBrace */: - case 125 /* closeBrace */: + case 98 /* b */: + pos++; + return "\b"; case 45 /* minus */: - case 124 /* bar */: - error2(Diagnostics.Unexpected_0_Did_you_mean_to_escape_it_with_backslash, pos, 1, String.fromCharCode(ch)); pos++; return String.fromCharCode(ch); + default: + if (scanCharacterClassEscape()) { + return ""; + } + return scanCharacterEscape( + /*atomEscape*/ + false + ); } + } else { return scanSourceCharacter(); } - function scanClassAtom() { - if (text2.charCodeAt(pos) === 92 /* backslash */) { + } + function scanCharacterClassEscape() { + Debug.assertEqual(charCodeUnchecked(pos - 1), 92 /* backslash */); + let isCharacterComplement = false; + const start2 = pos - 1; + const ch = charCodeChecked(pos); + switch (ch) { + case 100 /* d */: + case 68 /* D */: + case 115 /* s */: + case 83 /* S */: + case 119 /* w */: + case 87 /* W */: pos++; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 98 /* b */: - pos++; - return "\b"; - case 45 /* minus */: - pos++; - return String.fromCharCode(ch); - default: - if (scanCharacterClassEscape()) { - return ""; - } - return scanCharacterEscape( - /*atomEscape*/ - false - ); - } - } else { - return scanSourceCharacter(); - } - } - function scanCharacterClassEscape() { - Debug.assertEqual(text2.charCodeAt(pos - 1), 92 /* backslash */); - let isCharacterComplement = false; - const start2 = pos - 1; - const ch = text2.charCodeAt(pos); - switch (ch) { - case 100 /* d */: - case 68 /* D */: - case 115 /* s */: - case 83 /* S */: - case 119 /* w */: - case 87 /* W */: - pos++; - return true; - case 80 /* P */: - isCharacterComplement = true; - case 112 /* p */: + return true; + case 80 /* P */: + isCharacterComplement = true; + case 112 /* p */: + pos++; + if (charCodeChecked(pos) === 123 /* openBrace */) { pos++; - if (text2.charCodeAt(pos) === 123 /* openBrace */) { + const propertyNameOrValueStart = pos; + const propertyNameOrValue = scanWordCharacters(); + if (charCodeChecked(pos) === 61 /* equals */) { + const propertyName = nonBinaryUnicodeProperties.get(propertyNameOrValue); + if (pos === propertyNameOrValueStart) { + error2(Diagnostics.Expected_a_Unicode_property_name); + } else if (propertyName === void 0) { + error2(Diagnostics.Unknown_Unicode_property_name, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, nonBinaryUnicodeProperties.keys(), identity); + if (suggestion) { + error2(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); + } + } pos++; - const propertyNameOrValueStart = pos; - const propertyNameOrValue = scanWordCharacters(); - if (text2.charCodeAt(pos) === 61 /* equals */) { - const propertyName = nonBinaryUnicodeProperties.get(propertyNameOrValue); - if (pos === propertyNameOrValueStart) { - error2(Diagnostics.Expected_a_Unicode_property_name); - } else if (propertyName === void 0) { - error2(Diagnostics.Unknown_Unicode_property_name, propertyNameOrValueStart, pos - propertyNameOrValueStart); - const suggestion = getSpellingSuggestion(propertyNameOrValue, nonBinaryUnicodeProperties.keys(), identity); - if (suggestion) { - error2(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); - } + const propertyValueStart = pos; + const propertyValue = scanWordCharacters(); + if (pos === propertyValueStart) { + error2(Diagnostics.Expected_a_Unicode_property_value); + } else if (propertyName !== void 0 && !valuesOfNonBinaryUnicodeProperties[propertyName].has(propertyValue)) { + error2(Diagnostics.Unknown_Unicode_property_value, propertyValueStart, pos - propertyValueStart); + const suggestion = getSpellingSuggestion(propertyValue, valuesOfNonBinaryUnicodeProperties[propertyName], identity); + if (suggestion) { + error2(Diagnostics.Did_you_mean_0, propertyValueStart, pos - propertyValueStart, suggestion); } - pos++; - const propertyValueStart = pos; - const propertyValue = scanWordCharacters(); - if (pos === propertyValueStart) { - error2(Diagnostics.Expected_a_Unicode_property_value); - } else if (propertyName !== void 0 && !valuesOfNonBinaryUnicodeProperties[propertyName].has(propertyValue)) { - error2(Diagnostics.Unknown_Unicode_property_value, propertyValueStart, pos - propertyValueStart); - const suggestion = getSpellingSuggestion(propertyValue, valuesOfNonBinaryUnicodeProperties[propertyName], identity); - if (suggestion) { - error2(Diagnostics.Did_you_mean_0, propertyValueStart, pos - propertyValueStart, suggestion); - } + } + } else { + if (pos === propertyNameOrValueStart) { + error2(Diagnostics.Expected_a_Unicode_property_name_or_value); + } else if (binaryUnicodePropertiesOfStrings.has(propertyNameOrValue)) { + if (!unicodeSetsMode) { + error2(Diagnostics.Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else if (isCharacterComplement) { + error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, propertyNameOrValueStart, pos - propertyNameOrValueStart); + } else { + mayContainStrings = true; } - } else { - if (pos === propertyNameOrValueStart) { - error2(Diagnostics.Expected_a_Unicode_property_name_or_value); - } else if (binaryUnicodePropertiesOfStrings.has(propertyNameOrValue)) { - if (!unicodeSetsMode) { - error2(Diagnostics.Any_Unicode_property_that_would_possibly_match_more_than_a_single_character_is_only_available_when_the_Unicode_Sets_v_flag_is_set, propertyNameOrValueStart, pos - propertyNameOrValueStart); - } else if (isCharacterComplement) { - error2(Diagnostics.Anything_that_would_possibly_match_more_than_a_single_character_is_invalid_inside_a_negated_character_class, propertyNameOrValueStart, pos - propertyNameOrValueStart); - } else { - mayContainStrings = true; - } - } else if (!valuesOfNonBinaryUnicodeProperties.General_Category.has(propertyNameOrValue) && !binaryUnicodeProperties.has(propertyNameOrValue)) { - error2(Diagnostics.Unknown_Unicode_property_name_or_value, propertyNameOrValueStart, pos - propertyNameOrValueStart); - const suggestion = getSpellingSuggestion(propertyNameOrValue, [...valuesOfNonBinaryUnicodeProperties.General_Category, ...binaryUnicodeProperties, ...binaryUnicodePropertiesOfStrings], identity); - if (suggestion) { - error2(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); - } + } else if (!valuesOfNonBinaryUnicodeProperties.General_Category.has(propertyNameOrValue) && !binaryUnicodeProperties.has(propertyNameOrValue)) { + error2(Diagnostics.Unknown_Unicode_property_name_or_value, propertyNameOrValueStart, pos - propertyNameOrValueStart); + const suggestion = getSpellingSuggestion(propertyNameOrValue, [...valuesOfNonBinaryUnicodeProperties.General_Category, ...binaryUnicodeProperties, ...binaryUnicodePropertiesOfStrings], identity); + if (suggestion) { + error2(Diagnostics.Did_you_mean_0, propertyNameOrValueStart, pos - propertyNameOrValueStart, suggestion); } } - scanExpectedChar(125 /* closeBrace */); - if (!unicodeMode) { - error2(Diagnostics.Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); - } - } else if (unicodeMode) { - error2(Diagnostics._0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces, pos - 2, 2, String.fromCharCode(ch)); } - return true; - } - return false; - } - function scanWordCharacters() { - let value = ""; - while (pos < end2) { - const ch = text2.charCodeAt(pos); - if (!isWordCharacter(ch)) { - break; + scanExpectedChar(125 /* closeBrace */); + if (!anyUnicodeMode) { + error2(Diagnostics.Unicode_property_value_expressions_are_only_available_when_the_Unicode_u_flag_or_the_Unicode_Sets_v_flag_is_set, start2, pos - start2); + } + } else if (anyUnicodeModeOrNonAnnexB) { + error2(Diagnostics._0_must_be_followed_by_a_Unicode_property_value_expression_enclosed_in_braces, pos - 2, 2, String.fromCharCode(ch)); + } else { + pos--; + return false; } - value += String.fromCharCode(ch); - pos++; + return true; + } + return false; + } + function scanWordCharacters() { + let value = ""; + while (true) { + const ch = charCodeChecked(pos); + if (ch === -1 /* EOF */ || !isWordCharacter(ch)) { + break; } - return value; + value += String.fromCharCode(ch); + pos++; } - function scanSourceCharacter() { - const size = unicodeMode ? charSize(codePointAt(text2, pos)) : 1; - pos += size; - return text2.substring(pos - size, pos); + return value; + } + function scanSourceCharacter() { + const size = anyUnicodeMode ? charSize(charCodeChecked(pos)) : 1; + pos += size; + return size > 0 ? text.substring(pos - size, pos) : ""; + } + function scanExpectedChar(ch) { + if (charCodeChecked(pos) === ch) { + pos++; + } else { + error2(Diagnostics._0_expected, pos, 0, String.fromCharCode(ch)); } - function scanExpectedChar(ch) { - if (text2.charCodeAt(pos) === ch) { - pos++; + } + scanDisjunction( + /*isInGroup*/ + false + ); + forEach(groupNameReferences, (reference) => { + if (!(groupSpecifiers == null ? void 0 : groupSpecifiers.has(reference.name))) { + error2(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); + } + }); + forEach(decimalEscapes, (escape) => { + if (escape.value > numberOfCapturingGroups) { + if (numberOfCapturingGroups) { + error2(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos, numberOfCapturingGroups); } else { - error2(Diagnostics._0_expected, pos, 0, String.fromCharCode(ch)); + error2(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_no_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos); } } - scanDisjunction( - /*isInGroup*/ - false - ); - forEach(groupNameReferences, (reference) => { - if (!groupSpecifiers.has(reference.name)) { - error2(Diagnostics.There_is_no_capturing_group_named_0_in_this_regular_expression, reference.pos, reference.end - reference.pos, reference.name); - } - }); - forEach(decimalEscapes, (escape) => { - if (!annexB && escape.value > numberOfCapturingGroups) { - if (numberOfCapturingGroups) { - error2(Diagnostics.This_backreference_refers_to_a_group_that_does_not_exist_There_are_only_0_capturing_groups_in_this_regular_expression, escape.pos, escape.end - escape.pos, numberOfCapturingGroups); - } else { - error2(Diagnostics.This_backreference_is_invalid_because_the_containing_regular_expression_contains_no_capturing_groups, escape.pos, escape.end - escape.pos); - } - } - }); + }); + } + function checkRegularExpressionFlagAvailable(flag, pos2) { + const availableFrom = regExpFlagToFirstAvailableLanguageVersion.get(flag); + if (availableFrom && languageVersion < availableFrom) { + error2(Diagnostics.This_regular_expression_flag_is_only_available_when_targeting_0_or_later, pos2, 1, getNameOfScriptTarget(availableFrom)); } } function appendIfCommentDirective(commentDirectives2, text2, commentDirectiveRegEx, lineStart) { @@ -14381,9 +14336,9 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - let char = text.charCodeAt(pos); + let char = charCodeUnchecked(pos); if (char === 60 /* lessThan */) { - if (text.charCodeAt(pos + 1) === 47 /* slash */) { + if (charCodeUnchecked(pos + 1) === 47 /* slash */) { pos += 2; return token = 31 /* LessThanSlashToken */; } @@ -14396,7 +14351,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } let firstNonWhitespace = 0; while (pos < end) { - char = text.charCodeAt(pos); + char = charCodeUnchecked(pos); if (char === 123 /* openBrace */) { break; } @@ -14428,7 +14383,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { while (pos < end) { - const ch = text.charCodeAt(pos); + const ch = charCodeUnchecked(pos); if (ch === 45 /* minus */) { tokenValue += "-"; pos++; @@ -14446,7 +14401,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } function scanJsxAttributeValue() { fullStartPos = pos; - switch (text.charCodeAt(pos)) { + switch (charCodeUnchecked(pos)) { case 34 /* doubleQuote */: case 39 /* singleQuote */: tokenValue = scanString( @@ -14468,11 +14423,11 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - for (let ch = text.charCodeAt(pos); pos < end && (!isLineBreak(ch) && ch !== 96 /* backtick */); ch = codePointAt(text, ++pos)) { + for (let ch = charCodeUnchecked(pos); pos < end && (!isLineBreak(ch) && ch !== 96 /* backtick */); ch = codePointUnchecked(++pos)) { if (!inBackticks) { if (ch === 123 /* openBrace */) { break; - } else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(text.charCodeAt(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(text.charCodeAt(pos + 1)))) { + } else if (ch === 64 /* at */ && pos - 1 >= 0 && isWhiteSpaceSingleLine(charCodeUnchecked(pos - 1)) && !(pos + 1 < end && isWhiteSpaceLike(charCodeUnchecked(pos + 1)))) { break; } } @@ -14489,21 +14444,21 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end) { return token = 1 /* EndOfFileToken */; } - const ch = codePointAt(text, pos); + const ch = codePointUnchecked(pos); pos += charSize(ch); switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: case 12 /* formFeed */: case 32 /* space */: - while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) { + while (pos < end && isWhiteSpaceSingleLine(charCodeUnchecked(pos))) { pos++; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: return token = 60 /* AtToken */; case 13 /* carriageReturn */: - if (text.charCodeAt(pos) === 10 /* lineFeed */) { + if (charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } case 10 /* lineFeed */: @@ -14559,8 +14514,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } if (isIdentifierStart(ch, languageVersion)) { let char = ch; - while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */) - pos += charSize(char); + while (pos < end && isIdentifierPart(char = codePointUnchecked(pos), languageVersion) || char === 45 /* minus */) pos += charSize(char); tokenValue = text.substring(tokenStart, pos); if (char === 92 /* backslash */) { tokenValue += scanIdentifierParts(); @@ -14669,6 +14623,9 @@ function charSize(ch) { if (ch >= 65536) { return 2; } + if (ch === -1 /* EOF */) { + return 0; + } return 1; } function utf16EncodeAsStringFallback(codePoint) { @@ -14696,17 +14653,17 @@ var binaryUnicodeProperties = /* @__PURE__ */ new Set(["ASCII", "ASCII_Hex_Digit var binaryUnicodePropertiesOfStrings = /* @__PURE__ */ new Set(["Basic_Emoji", "Emoji_Keycap_Sequence", "RGI_Emoji_Modifier_Sequence", "RGI_Emoji_Flag_Sequence", "RGI_Emoji_Tag_Sequence", "RGI_Emoji_ZWJ_Sequence", "RGI_Emoji"]); var valuesOfNonBinaryUnicodeProperties = { General_Category: /* @__PURE__ */ new Set(["C", "Other", "Cc", "Control", "cntrl", "Cf", "Format", "Cn", "Unassigned", "Co", "Private_Use", "Cs", "Surrogate", "L", "Letter", "LC", "Cased_Letter", "Ll", "Lowercase_Letter", "Lm", "Modifier_Letter", "Lo", "Other_Letter", "Lt", "Titlecase_Letter", "Lu", "Uppercase_Letter", "M", "Mark", "Combining_Mark", "Mc", "Spacing_Mark", "Me", "Enclosing_Mark", "Mn", "Nonspacing_Mark", "N", "Number", "Nd", "Decimal_Number", "digit", "Nl", "Letter_Number", "No", "Other_Number", "P", "Punctuation", "punct", "Pc", "Connector_Punctuation", "Pd", "Dash_Punctuation", "Pe", "Close_Punctuation", "Pf", "Final_Punctuation", "Pi", "Initial_Punctuation", "Po", "Other_Punctuation", "Ps", "Open_Punctuation", "S", "Symbol", "Sc", "Currency_Symbol", "Sk", "Modifier_Symbol", "Sm", "Math_Symbol", "So", "Other_Symbol", "Z", "Separator", "Zl", "Line_Separator", "Zp", "Paragraph_Separator", "Zs", "Space_Separator"]), - Script: /* @__PURE__ */ new Set(["Adlm", "Adlam", "Aghb", "Caucasian_Albanian", "Ahom", "Ahom", "Arab", "Arabic", "Armi", "Imperial_Aramaic", "Armn", "Armenian", "Avst", "Avestan", "Bali", "Balinese", "Bamu", "Bamum", "Bass", "Bassa_Vah", "Batk", "Batak", "Beng", "Bengali", "Bhks", "Bhaiksuki", "Bopo", "Bopomofo", "Brah", "Brahmi", "Brai", "Braille", "Bugi", "Buginese", "Buhd", "Buhid", "Cakm", "Chakma", "Cans", "Canadian_Aboriginal", "Cari", "Carian", "Cham", "Cham", "Cher", "Cherokee", "Chrs", "Chorasmian", "Copt", "Coptic", "Qaac", "Cpmn", "Cypro_Minoan", "Cprt", "Cypriot", "Cyrl", "Cyrillic", "Deva", "Devanagari", "Diak", "Dives_Akuru", "Dogr", "Dogra", "Dsrt", "Deseret", "Dupl", "Duployan", "Egyp", "Egyptian_Hieroglyphs", "Elba", "Elbasan", "Elym", "Elymaic", "Ethi", "Ethiopic", "Geor", "Georgian", "Glag", "Glagolitic", "Gong", "Gunjala_Gondi", "Gonm", "Masaram_Gondi", "Goth", "Gothic", "Gran", "Grantha", "Grek", "Greek", "Gujr", "Gujarati", "Guru", "Gurmukhi", "Hang", "Hangul", "Hani", "Han", "Hano", "Hanunoo", "Hatr", "Hatran", "Hebr", "Hebrew", "Hira", "Hiragana", "Hluw", "Anatolian_Hieroglyphs", "Hmng", "Pahawh_Hmong", "Hmnp", "Nyiakeng_Puachue_Hmong", "Hrkt", "Katakana_Or_Hiragana", "Hung", "Old_Hungarian", "Ital", "Old_Italic", "Java", "Javanese", "Kali", "Kayah_Li", "Kana", "Katakana", "Kawi", "Kawi", "Khar", "Kharoshthi", "Khmr", "Khmer", "Khoj", "Khojki", "Kits", "Khitan_Small_Script", "Knda", "Kannada", "Kthi", "Kaithi", "Lana", "Tai_Tham", "Laoo", "Lao", "Latn", "Latin", "Lepc", "Lepcha", "Limb", "Limbu", "Lina", "Linear_A", "Linb", "Linear_B", "Lisu", "Lisu", "Lyci", "Lycian", "Lydi", "Lydian", "Mahj", "Mahajani", "Maka", "Makasar", "Mand", "Mandaic", "Mani", "Manichaean", "Marc", "Marchen", "Medf", "Medefaidrin", "Mend", "Mende_Kikakui", "Merc", "Meroitic_Cursive", "Mero", "Meroitic_Hieroglyphs", "Mlym", "Malayalam", "Modi", "Modi", "Mong", "Mongolian", "Mroo", "Mro", "Mtei", "Meetei_Mayek", "Mult", "Multani", "Mymr", "Myanmar", "Nagm", "Nag_Mundari", "Nand", "Nandinagari", "Narb", "Old_North_Arabian", "Nbat", "Nabataean", "Newa", "Newa", "Nkoo", "Nko", "Nshu", "Nushu", "Ogam", "Ogham", "Olck", "Ol_Chiki", "Orkh", "Old_Turkic", "Orya", "Oriya", "Osge", "Osage", "Osma", "Osmanya", "Ougr", "Old_Uyghur", "Palm", "Palmyrene", "Pauc", "Pau_Cin_Hau", "Perm", "Old_Permic", "Phag", "Phags_Pa", "Phli", "Inscriptional_Pahlavi", "Phlp", "Psalter_Pahlavi", "Phnx", "Phoenician", "Plrd", "Miao", "Prti", "Inscriptional_Parthian", "Rjng", "Rejang", "Rohg", "Hanifi_Rohingya", "Runr", "Runic", "Samr", "Samaritan", "Sarb", "Old_South_Arabian", "Saur", "Saurashtra", "Sgnw", "SignWriting", "Shaw", "Shavian", "Shrd", "Sharada", "Sidd", "Siddham", "Sind", "Khudawadi", "Sinh", "Sinhala", "Sogd", "Sogdian", "Sogo", "Old_Sogdian", "Sora", "Sora_Sompeng", "Soyo", "Soyombo", "Sund", "Sundanese", "Sylo", "Syloti_Nagri", "Syrc", "Syriac", "Tagb", "Tagbanwa", "Takr", "Takri", "Tale", "Tai_Le", "Talu", "New_Tai_Lue", "Taml", "Tamil", "Tang", "Tangut", "Tavt", "Tai_Viet", "Telu", "Telugu", "Tfng", "Tifinagh", "Tglg", "Tagalog", "Thaa", "Thaana", "Thai", "Thai", "Tibt", "Tibetan", "Tirh", "Tirhuta", "Tnsa", "Tangsa", "Toto", "Toto", "Ugar", "Ugaritic", "Vaii", "Vai", "Vith", "Vithkuqi", "Wara", "Warang_Citi", "Wcho", "Wancho", "Xpeo", "Old_Persian", "Xsux", "Cuneiform", "Yezi", "Yezidi", "Yiii", "Yi", "Zanb", "Zanabazar_Square", "Zinh", "Inherited", "Qaai", "Zyyy", "Common", "Zzzz", "Unknown"]), - Script_Extensions: /* @__PURE__ */ new Set() - // Currently empty + Script: /* @__PURE__ */ new Set(["Adlm", "Adlam", "Aghb", "Caucasian_Albanian", "Ahom", "Arab", "Arabic", "Armi", "Imperial_Aramaic", "Armn", "Armenian", "Avst", "Avestan", "Bali", "Balinese", "Bamu", "Bamum", "Bass", "Bassa_Vah", "Batk", "Batak", "Beng", "Bengali", "Bhks", "Bhaiksuki", "Bopo", "Bopomofo", "Brah", "Brahmi", "Brai", "Braille", "Bugi", "Buginese", "Buhd", "Buhid", "Cakm", "Chakma", "Cans", "Canadian_Aboriginal", "Cari", "Carian", "Cham", "Cher", "Cherokee", "Chrs", "Chorasmian", "Copt", "Coptic", "Qaac", "Cpmn", "Cypro_Minoan", "Cprt", "Cypriot", "Cyrl", "Cyrillic", "Deva", "Devanagari", "Diak", "Dives_Akuru", "Dogr", "Dogra", "Dsrt", "Deseret", "Dupl", "Duployan", "Egyp", "Egyptian_Hieroglyphs", "Elba", "Elbasan", "Elym", "Elymaic", "Ethi", "Ethiopic", "Geor", "Georgian", "Glag", "Glagolitic", "Gong", "Gunjala_Gondi", "Gonm", "Masaram_Gondi", "Goth", "Gothic", "Gran", "Grantha", "Grek", "Greek", "Gujr", "Gujarati", "Guru", "Gurmukhi", "Hang", "Hangul", "Hani", "Han", "Hano", "Hanunoo", "Hatr", "Hatran", "Hebr", "Hebrew", "Hira", "Hiragana", "Hluw", "Anatolian_Hieroglyphs", "Hmng", "Pahawh_Hmong", "Hmnp", "Nyiakeng_Puachue_Hmong", "Hrkt", "Katakana_Or_Hiragana", "Hung", "Old_Hungarian", "Ital", "Old_Italic", "Java", "Javanese", "Kali", "Kayah_Li", "Kana", "Katakana", "Kawi", "Khar", "Kharoshthi", "Khmr", "Khmer", "Khoj", "Khojki", "Kits", "Khitan_Small_Script", "Knda", "Kannada", "Kthi", "Kaithi", "Lana", "Tai_Tham", "Laoo", "Lao", "Latn", "Latin", "Lepc", "Lepcha", "Limb", "Limbu", "Lina", "Linear_A", "Linb", "Linear_B", "Lisu", "Lyci", "Lycian", "Lydi", "Lydian", "Mahj", "Mahajani", "Maka", "Makasar", "Mand", "Mandaic", "Mani", "Manichaean", "Marc", "Marchen", "Medf", "Medefaidrin", "Mend", "Mende_Kikakui", "Merc", "Meroitic_Cursive", "Mero", "Meroitic_Hieroglyphs", "Mlym", "Malayalam", "Modi", "Mong", "Mongolian", "Mroo", "Mro", "Mtei", "Meetei_Mayek", "Mult", "Multani", "Mymr", "Myanmar", "Nagm", "Nag_Mundari", "Nand", "Nandinagari", "Narb", "Old_North_Arabian", "Nbat", "Nabataean", "Newa", "Nkoo", "Nko", "Nshu", "Nushu", "Ogam", "Ogham", "Olck", "Ol_Chiki", "Orkh", "Old_Turkic", "Orya", "Oriya", "Osge", "Osage", "Osma", "Osmanya", "Ougr", "Old_Uyghur", "Palm", "Palmyrene", "Pauc", "Pau_Cin_Hau", "Perm", "Old_Permic", "Phag", "Phags_Pa", "Phli", "Inscriptional_Pahlavi", "Phlp", "Psalter_Pahlavi", "Phnx", "Phoenician", "Plrd", "Miao", "Prti", "Inscriptional_Parthian", "Rjng", "Rejang", "Rohg", "Hanifi_Rohingya", "Runr", "Runic", "Samr", "Samaritan", "Sarb", "Old_South_Arabian", "Saur", "Saurashtra", "Sgnw", "SignWriting", "Shaw", "Shavian", "Shrd", "Sharada", "Sidd", "Siddham", "Sind", "Khudawadi", "Sinh", "Sinhala", "Sogd", "Sogdian", "Sogo", "Old_Sogdian", "Sora", "Sora_Sompeng", "Soyo", "Soyombo", "Sund", "Sundanese", "Sylo", "Syloti_Nagri", "Syrc", "Syriac", "Tagb", "Tagbanwa", "Takr", "Takri", "Tale", "Tai_Le", "Talu", "New_Tai_Lue", "Taml", "Tamil", "Tang", "Tangut", "Tavt", "Tai_Viet", "Telu", "Telugu", "Tfng", "Tifinagh", "Tglg", "Tagalog", "Thaa", "Thaana", "Thai", "Tibt", "Tibetan", "Tirh", "Tirhuta", "Tnsa", "Tangsa", "Toto", "Ugar", "Ugaritic", "Vaii", "Vai", "Vith", "Vithkuqi", "Wara", "Warang_Citi", "Wcho", "Wancho", "Xpeo", "Old_Persian", "Xsux", "Cuneiform", "Yezi", "Yezidi", "Yiii", "Yi", "Zanb", "Zanabazar_Square", "Zinh", "Inherited", "Qaai", "Zyyy", "Common", "Zzzz", "Unknown"]), + Script_Extensions: void 0 }; +valuesOfNonBinaryUnicodeProperties.Script_Extensions = valuesOfNonBinaryUnicodeProperties.Script; // src/compiler/utilitiesPublic.ts function isExternalModuleNameRelative(moduleName) { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } function sortAndDeduplicateDiagnostics(diagnostics) { - return sortAndDeduplicate(diagnostics, compareDiagnostics); + return sortAndDeduplicate(diagnostics, compareDiagnostics, diagnosticsEqualityComparer); } function getDefaultLibFileName(options) { switch (getEmitScriptTarget(options)) { @@ -15104,8 +15061,7 @@ function getNonAssignedNameOfDeclaration(declaration) { return declaration.name; } function getNameOfDeclaration(declaration) { - if (declaration === void 0) - return void 0; + if (declaration === void 0) return void 0; return getNonAssignedNameOfDeclaration(declaration) || (isFunctionExpression(declaration) || isArrowFunction(declaration) || isClassExpression(declaration) ? getAssignedName(declaration) : void 0); } function getAssignedName(node) { @@ -15304,8 +15260,7 @@ function getJSDocReturnType(node) { } function getJSDocTagsWorker(node, noCache) { var _a; - if (!canHaveJSDoc(node)) - return emptyArray; + if (!canHaveJSDoc(node)) return emptyArray; let tags = (_a = node.jsDoc) == null ? void 0 : _a.jsDocCache; if (tags === void 0 || noCache) { const comments = getJSDocCommentsAndTags(node, noCache); @@ -15347,7 +15302,7 @@ function getTextOfJSDocComment(comment) { function formatJSDocLink(link) { const kind = link.kind === 324 /* JSDocLink */ ? "link" : link.kind === 325 /* JSDocLinkCode */ ? "linkcode" : "linkplain"; const name = link.name ? entityNameToString(link.name) : ""; - const space = link.name && link.text.startsWith("://") ? "" : " "; + const space = link.name && (link.text === "" || link.text.startsWith("://")) ? "" : " "; return `{@${kind} ${name}${space}${link.text}}`; } function getEffectiveTypeParameterDeclarations(node) { @@ -16060,7 +16015,7 @@ function canHaveLocals(node) { } } function isDeclarationKind(kind) { - return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 346 /* JSDocTypedefTag */ || kind === 338 /* JSDocCallbackTag */ || kind === 348 /* JSDocPropertyTag */; + return kind === 219 /* ArrowFunction */ || kind === 208 /* BindingElement */ || kind === 263 /* ClassDeclaration */ || kind === 231 /* ClassExpression */ || kind === 175 /* ClassStaticBlockDeclaration */ || kind === 176 /* Constructor */ || kind === 266 /* EnumDeclaration */ || kind === 306 /* EnumMember */ || kind === 281 /* ExportSpecifier */ || kind === 262 /* FunctionDeclaration */ || kind === 218 /* FunctionExpression */ || kind === 177 /* GetAccessor */ || kind === 273 /* ImportClause */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 276 /* ImportSpecifier */ || kind === 264 /* InterfaceDeclaration */ || kind === 291 /* JsxAttribute */ || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 267 /* ModuleDeclaration */ || kind === 270 /* NamespaceExportDeclaration */ || kind === 274 /* NamespaceImport */ || kind === 280 /* NamespaceExport */ || kind === 169 /* Parameter */ || kind === 303 /* PropertyAssignment */ || kind === 172 /* PropertyDeclaration */ || kind === 171 /* PropertySignature */ || kind === 178 /* SetAccessor */ || kind === 304 /* ShorthandPropertyAssignment */ || kind === 265 /* TypeAliasDeclaration */ || kind === 168 /* TypeParameter */ || kind === 260 /* VariableDeclaration */ || kind === 346 /* JSDocTypedefTag */ || kind === 338 /* JSDocCallbackTag */ || kind === 348 /* JSDocPropertyTag */ || kind === 202 /* NamedTupleMember */; } function isDeclarationStatementKind(kind) { return kind === 262 /* FunctionDeclaration */ || kind === 282 /* MissingDeclaration */ || kind === 263 /* ClassDeclaration */ || kind === 264 /* InterfaceDeclaration */ || kind === 265 /* TypeAliasDeclaration */ || kind === 266 /* EnumDeclaration */ || kind === 267 /* ModuleDeclaration */ || kind === 272 /* ImportDeclaration */ || kind === 271 /* ImportEqualsDeclaration */ || kind === 278 /* ExportDeclaration */ || kind === 277 /* ExportAssignment */ || kind === 270 /* NamespaceExportDeclaration */; @@ -16085,8 +16040,7 @@ function isStatement(node) { return isStatementKindButNotDeclarationKind(kind) || isDeclarationStatementKind(kind) || isBlockStatement(node); } function isBlockStatement(node) { - if (node.kind !== 241 /* Block */) - return false; + if (node.kind !== 241 /* Block */) return false; if (node.parent !== void 0) { if (node.parent.kind === 258 /* TryStatement */ || node.parent.kind === 299 /* CatchClause */) { return false; @@ -16142,8 +16096,7 @@ function isGetAccessor(node) { return node.kind === 177 /* GetAccessor */; } function hasJSDocNodes(node) { - if (!canHaveJSDoc(node)) - return false; + if (!canHaveJSDoc(node)) return false; const { jsDoc } = node; return !!jsDoc && jsDoc.length > 0; } @@ -16328,12 +16281,9 @@ function optionsHaveChanges(oldOptions, newOptions, optionDeclarations2) { function forEachAncestor(node, callback) { while (true) { const res = callback(node); - if (res === "quit") - return void 0; - if (res !== void 0) - return res; - if (isSourceFile(node)) - return void 0; + if (res === "quit") return void 0; + if (res !== void 0) return res; + if (isSourceFile(node)) return void 0; node = node.parent; } } @@ -16412,8 +16362,7 @@ function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, pack moduleReference, mangleScopedPackageName(packageName) ); - if (result) - result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); + if (result) result.repopulateInfo = () => ({ moduleReference, mode, packageName: packageName === moduleReference ? void 0 : packageName }); return result; } function packageIdIsEqual(a, b) { @@ -16516,38 +16465,25 @@ function nodeIsPresent(node) { return !nodeIsMissing(node); } function isGrammarError(parent2, child) { - if (isTypeParameterDeclaration(parent2)) - return child === parent2.expression; - if (isClassStaticBlockDeclaration(parent2)) - return child === parent2.modifiers; - if (isPropertySignature(parent2)) - return child === parent2.initializer; - if (isPropertyDeclaration(parent2)) - return child === parent2.questionToken && isAutoAccessorPropertyDeclaration(parent2); - if (isPropertyAssignment(parent2)) - return child === parent2.modifiers || child === parent2.questionToken || child === parent2.exclamationToken || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); - if (isShorthandPropertyAssignment(parent2)) - return child === parent2.equalsToken || child === parent2.modifiers || child === parent2.questionToken || child === parent2.exclamationToken || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); - if (isMethodDeclaration(parent2)) - return child === parent2.exclamationToken; - if (isConstructorDeclaration(parent2)) - return child === parent2.typeParameters || child === parent2.type || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); - if (isGetAccessorDeclaration(parent2)) - return child === parent2.typeParameters || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); - if (isSetAccessorDeclaration(parent2)) - return child === parent2.typeParameters || child === parent2.type || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); - if (isNamespaceExportDeclaration(parent2)) - return child === parent2.modifiers || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); + if (isTypeParameterDeclaration(parent2)) return child === parent2.expression; + if (isClassStaticBlockDeclaration(parent2)) return child === parent2.modifiers; + if (isPropertySignature(parent2)) return child === parent2.initializer; + if (isPropertyDeclaration(parent2)) return child === parent2.questionToken && isAutoAccessorPropertyDeclaration(parent2); + if (isPropertyAssignment(parent2)) return child === parent2.modifiers || child === parent2.questionToken || child === parent2.exclamationToken || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); + if (isShorthandPropertyAssignment(parent2)) return child === parent2.equalsToken || child === parent2.modifiers || child === parent2.questionToken || child === parent2.exclamationToken || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); + if (isMethodDeclaration(parent2)) return child === parent2.exclamationToken; + if (isConstructorDeclaration(parent2)) return child === parent2.typeParameters || child === parent2.type || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); + if (isGetAccessorDeclaration(parent2)) return child === parent2.typeParameters || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); + if (isSetAccessorDeclaration(parent2)) return child === parent2.typeParameters || child === parent2.type || isGrammarErrorElement(parent2.typeParameters, child, isTypeParameterDeclaration); + if (isNamespaceExportDeclaration(parent2)) return child === parent2.modifiers || isGrammarErrorElement(parent2.modifiers, child, isModifierLike); return false; } function isGrammarErrorElement(nodeArray, child, isElement) { - if (!nodeArray || isArray(child) || !isElement(child)) - return false; + if (!nodeArray || isArray(child) || !isElement(child)) return false; return contains(nodeArray, child); } function insertStatementsAfterPrologue(to, from, isPrologueDirective2) { - if (from === void 0 || from.length === 0) - return to; + if (from === void 0 || from.length === 0) return to; let statementIndex = 0; for (; statementIndex < to.length; ++statementIndex) { if (!isPrologueDirective2(to[statementIndex])) { @@ -16558,8 +16494,7 @@ function insertStatementsAfterPrologue(to, from, isPrologueDirective2) { return to; } function insertStatementAfterPrologue(to, statement, isPrologueDirective2) { - if (statement === void 0) - return to; + if (statement === void 0) return to; let statementIndex = 0; for (; statementIndex < to.length; ++statementIndex) { if (!isPrologueDirective2(to[statementIndex])) { @@ -17377,8 +17312,7 @@ function tryGetTextOfPropertyName(name) { case 15 /* NoSubstitutionTemplateLiteral */: return escapeLeadingUnderscores(name.text); case 167 /* ComputedPropertyName */: - if (isStringOrNumericLiteralLike(name.expression)) - return escapeLeadingUnderscores(name.expression.text); + if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; case 295 /* JsxNamespacedName */: return getEscapedTextOfJsxNamespacedName(name); @@ -17405,7 +17339,7 @@ function entityNameToString(name) { return Debug.assertNever(name.name); } case 311 /* JSDocMemberName */: - return entityNameToString(name.left) + entityNameToString(name.right); + return entityNameToString(name.left) + "#" + entityNameToString(name.right); case 295 /* JsxNamespacedName */: return entityNameToString(name.namespace) + ":" + entityNameToString(name.name); default: @@ -17447,7 +17381,8 @@ function createFileDiagnosticFromMessageChain(file, start, length2, messageChain code: messageChain.code, category: messageChain.category, messageText: messageChain.next ? messageChain : messageChain.messageText, - relatedInformation + relatedInformation, + canonicalHead: messageChain.canonicalHead }; } function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) { @@ -17479,6 +17414,12 @@ function createDiagnosticForRange(sourceFile, range, message) { messageText: message.message }; } +function getCanonicalDiagnostic(message, ...args) { + return { + code: message.code, + messageText: formatMessage(message, ...args) + }; +} function getSpanOfTokenAtPosition(sourceFile, pos) { const scanner2 = createScanner( sourceFile.languageVersion, @@ -17574,6 +17515,26 @@ function getErrorSpanForNode(sourceFile, node) { const pos2 = skipTrivia(sourceFile.text, node.tagName.pos); return getSpanOfTokenAtPosition(sourceFile, pos2); } + case 176 /* Constructor */: { + const constructorDeclaration = node; + const start = skipTrivia(sourceFile.text, constructorDeclaration.pos); + const scanner2 = createScanner( + sourceFile.languageVersion, + /*skipTrivia*/ + true, + sourceFile.languageVariant, + sourceFile.text, + /*onError*/ + void 0, + start + ); + let token = scanner2.scan(); + while (token !== 137 /* ConstructorKeyword */ && token !== 1 /* EndOfFileToken */) { + token = scanner2.scan(); + } + const end = scanner2.getTokenEnd(); + return createTextSpanFromBounds(start, end); + } } if (errorNode === void 0) { return getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -17653,7 +17614,8 @@ function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { } function getJSDocCommentRanges(node, text) { const commentRanges = node.kind === 169 /* Parameter */ || node.kind === 168 /* TypeParameter */ || node.kind === 218 /* FunctionExpression */ || node.kind === 219 /* ArrowFunction */ || node.kind === 217 /* ParenthesizedExpression */ || node.kind === 260 /* VariableDeclaration */ || node.kind === 281 /* ExportSpecifier */ ? concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) : getLeadingCommentRanges(text, node.pos); - return filter(commentRanges, (comment) => text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); + return filter(commentRanges, (comment) => comment.end <= node.end && // Due to parse errors sometime empty parameter may get comments assigned to it that end up not in parameter range + text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ && text.charCodeAt(comment.pos + 3) !== 47 /* slash */); } var fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; @@ -17848,13 +17810,11 @@ function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 261 /* VariableDeclarationList */ && node.parent.parent.kind === 243 /* VariableStatement */; } function isCommonJsExportedExpression(node) { - if (!isInJSFile(node)) - return false; + if (!isInJSFile(node)) return false; return isObjectLiteralExpression(node.parent) && isBinaryExpression(node.parent.parent) && getAssignmentDeclarationKind(node.parent.parent) === 2 /* ModuleExports */ || isCommonJsExportPropertyAssignment(node.parent); } function isCommonJsExportPropertyAssignment(node) { - if (!isInJSFile(node)) - return false; + if (!isInJSFile(node)) return false; return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 1 /* ExportsProperty */; } function isValidESSymbolDeclaration(node) { @@ -17901,8 +17861,7 @@ function isThisTypePredicate(predicate) { } function forEachPropertyAssignment(objectLiteral, key, callback, key2) { return forEach(objectLiteral == null ? void 0 : objectLiteral.properties, (property) => { - if (!isPropertyAssignment(property)) - return void 0; + if (!isPropertyAssignment(property)) return void 0; const propName = tryGetTextOfPropertyName(property.name); return key === propName || key2 && key2 === propName ? callback(property) : void 0; }); @@ -18150,8 +18109,7 @@ function nodeCanBeDecorated(useLegacyDecorators, node, parent2, grandparent) { case 174 /* MethodDeclaration */: return node.body !== void 0 && parent2 !== void 0 && (useLegacyDecorators ? isClassDeclaration(parent2) : isClassLike(parent2)); case 169 /* Parameter */: - if (!useLegacyDecorators) - return false; + if (!useLegacyDecorators) return false; return parent2 !== void 0 && parent2.body !== void 0 && (parent2.kind === 176 /* Constructor */ || parent2.kind === 174 /* MethodDeclaration */ || parent2.kind === 178 /* SetAccessor */) && getThisParameter(parent2) !== node && grandparent !== void 0 && grandparent.kind === 263 /* ClassDeclaration */; } return false; @@ -18177,8 +18135,7 @@ function childIsDecorated(useLegacyDecorators, node, parent2) { } } function classOrConstructorParameterIsDecorated(useLegacyDecorators, node) { - if (nodeIsDecorated(useLegacyDecorators, node)) - return true; + if (nodeIsDecorated(useLegacyDecorators, node)) return true; const constructor = getFirstConstructorWithBody(node); return !!constructor && childIsDecorated(useLegacyDecorators, constructor, node); } @@ -18199,10 +18156,8 @@ function classElementOrClassElementParameterIsDecorated(useLegacyDecorators, nod } if (parameters) { for (const parameter of parameters) { - if (parameterIsThisKeyword(parameter)) - continue; - if (nodeIsDecorated(useLegacyDecorators, parameter, node, parent2)) - return true; + if (parameterIsThisKeyword(parameter)) continue; + if (nodeIsDecorated(useLegacyDecorators, parameter, node, parent2)) return true; } } return false; @@ -18782,13 +18737,11 @@ function isDefaultImport(node) { function forEachImportClauseDeclaration(node, action) { if (node.name) { const result = action(node); - if (result) - return result; + if (result) return result; } if (node.namedBindings) { const result = isNamespaceImport(node.namedBindings) ? action(node.namedBindings) : forEach(node.namedBindings.elements, action); - if (result) - return result; + if (result) return result; } } function hasQuestionToken(node) { @@ -19171,8 +19124,7 @@ function walkUpParenthesizedTypesAndGetParentAndChild(node) { return [child, node]; } function skipTypeParentheses(node) { - while (isParenthesizedTypeNode(node)) - node = node.type; + while (isParenthesizedTypeNode(node)) node = node.type; return node; } function skipParentheses(node, excludeJSDocTypeAssertions) { @@ -19188,8 +19140,7 @@ function isDeleteTarget(node) { } function isNodeDescendantOf(node, ancestor) { while (node) { - if (node === ancestor) - return true; + if (node === ancestor) return true; node = node.parent; } return false; @@ -19203,8 +19154,7 @@ function getDeclarationFromName(name) { case 11 /* StringLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: case 9 /* NumericLiteral */: - if (isComputedPropertyName(parent2)) - return parent2.parent; + if (isComputedPropertyName(parent2)) return parent2.parent; case 80 /* Identifier */: if (isDeclaration(parent2)) { return parent2.name === name ? parent2 : void 0; @@ -19536,8 +19486,7 @@ function isNamedEvaluationSource(node) { return false; } function isNamedEvaluation(node, cb) { - if (!isNamedEvaluationSource(node)) - return false; + if (!isNamedEvaluationSource(node)) return false; switch (node.kind) { case 303 /* PropertyAssignment */: return isAnonymousFunctionDefinition(node.initializer, cb); @@ -19830,6 +19779,9 @@ function createDiagnosticCollection() { if (result >= 0) { return diagnostics[result]; } + if (~result > 0 && diagnosticsEqualityComparer(diagnostic, diagnostics[~result - 1])) { + return diagnostics[~result - 1]; + } return void 0; } function add(diagnostic) { @@ -19848,7 +19800,7 @@ function createDiagnosticCollection() { } diagnostics = nonFileDiagnostics; } - insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation); + insertSorted(diagnostics, diagnostic, compareDiagnosticsSkipRelatedInformation, diagnosticsEqualityComparer); } function getGlobalDiagnostics() { hasReadNonFileDiagnostics = true; @@ -19996,13 +19948,11 @@ function createTextWriter(newLine) { } } function write(s) { - if (s) - hasTrailingComment = false; + if (s) hasTrailingComment = false; writeText(s); } function writeComment(s) { - if (s) - hasTrailingComment = true; + if (s) hasTrailingComment = true; writeText(s); } function reset2() { @@ -20202,8 +20152,7 @@ function getPossibleOriginalInputExtensionForExtension(path) { } function getPathsBasePath(options, host) { var _a; - if (!options.paths) - return void 0; + if (!options.paths) return void 0; return options.baseUrl ?? Debug.checkDefined(options.pathsBasePath || ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { @@ -20225,29 +20174,19 @@ function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) { } function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) { const options = host.getCompilerOptions(); - if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) - return false; - if (sourceFile.isDeclarationFile) - return false; - if (host.isSourceFileFromExternalLibrary(sourceFile)) - return false; - if (forceDtsEmit) - return true; - if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) - return false; - if (!isJsonSourceFile(sourceFile)) - return true; - if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) - return false; - if (options.outFile) - return true; - if (!options.outDir) - return false; + if (options.noEmitForJsFiles && isSourceFileJS(sourceFile)) return false; + if (sourceFile.isDeclarationFile) return false; + if (host.isSourceFileFromExternalLibrary(sourceFile)) return false; + if (forceDtsEmit) return true; + if (host.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) return false; + if (!isJsonSourceFile(sourceFile)) return true; + if (host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) return false; + if (options.outFile) return true; + if (!options.outDir) return false; if (options.rootDir || options.composite && options.configFilePath) { const commonDir = getNormalizedAbsolutePath(getCommonSourceDirectory(options, () => [], host.getCurrentDirectory(), host.getCanonicalFileName), host.getCurrentDirectory()); const outputPath = getSourceFilePathInNewDirWorker(sourceFile.fileName, options.outDir, host.getCurrentDirectory(), commonDir, host.getCanonicalFileName); - if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) - return false; + if (comparePaths(sourceFile.fileName, outputPath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */) return false; } return true; } @@ -20382,11 +20321,10 @@ function getAllAccessorDeclarations(declarations, accessor) { }; } function getEffectiveTypeAnnotationNode(node) { - if (!isInJSFile(node) && isFunctionDeclaration(node)) - return void 0; + if (!isInJSFile(node) && isFunctionDeclaration(node)) return void 0; + if (isTypeAliasDeclaration(node)) return void 0; const type = node.type; - if (type || !isInJSFile(node)) - return type; + if (type || !isInJSFile(node)) return type; return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); } function getTypeAnnotationNode(node) { @@ -20630,19 +20568,13 @@ function getRawJSDocModifierFlagsNoCache(node) { let flags = 0 /* None */; if (!!node.parent && !isParameter(node)) { if (isInJSFile(node)) { - if (getJSDocPublicTagNoCache(node)) - flags |= 8388608 /* JSDocPublic */; - if (getJSDocPrivateTagNoCache(node)) - flags |= 16777216 /* JSDocPrivate */; - if (getJSDocProtectedTagNoCache(node)) - flags |= 33554432 /* JSDocProtected */; - if (getJSDocReadonlyTagNoCache(node)) - flags |= 67108864 /* JSDocReadonly */; - if (getJSDocOverrideTagNoCache(node)) - flags |= 134217728 /* JSDocOverride */; - } - if (getJSDocDeprecatedTagNoCache(node)) - flags |= 65536 /* Deprecated */; + if (getJSDocPublicTagNoCache(node)) flags |= 8388608 /* JSDocPublic */; + if (getJSDocPrivateTagNoCache(node)) flags |= 16777216 /* JSDocPrivate */; + if (getJSDocProtectedTagNoCache(node)) flags |= 33554432 /* JSDocProtected */; + if (getJSDocReadonlyTagNoCache(node)) flags |= 67108864 /* JSDocReadonly */; + if (getJSDocOverrideTagNoCache(node)) flags |= 134217728 /* JSDocOverride */; + } + if (getJSDocDeprecatedTagNoCache(node)) flags |= 65536 /* Deprecated */; } return flags; } @@ -20838,11 +20770,9 @@ function isEmptyArrayLiteral(expression) { return expression.kind === 209 /* ArrayLiteralExpression */ && expression.elements.length === 0; } function getLocalSymbolForExportDefault(symbol) { - if (!isExportDefaultSymbol(symbol) || !symbol.declarations) - return void 0; + if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return void 0; for (const decl of symbol.declarations) { - if (decl.localSymbol) - return decl.localSymbol; + if (decl.localSymbol) return decl.localSymbol; } return void 0; } @@ -20962,8 +20892,7 @@ function base64decode(host, input) { } function readJsonOrUndefined(path, hostOrText) { const jsonText = isString(hostOrText) ? hostOrText : hostOrText.readFile(path); - if (!jsonText) - return void 0; + if (!jsonText) return void 0; const result = parseConfigFileTextToJson(path, jsonText); return !result.error ? result.config : void 0; } @@ -21268,8 +21197,7 @@ function showModuleSpecifier({ moduleSpecifier }) { function getLastChild(node) { let lastChild; forEachChild(node, (child) => { - if (nodeIsPresent(child)) - lastChild = child; + if (nodeIsPresent(child)) lastChild = child; }, (children) => { for (let i = children.length - 1; i >= 0; i--) { if (nodeIsPresent(children[i])) { @@ -21609,61 +21537,125 @@ function compareDiagnostics(d1, d2) { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || 0 /* EqualTo */; } function compareDiagnosticsSkipRelatedInformation(d1, d2) { - return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(d1.code, d2.code) || compareMessageText(d1.messageText, d2.messageText) || 0 /* EqualTo */; + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || compareValues(d1.start, d2.start) || compareValues(d1.length, d2.length) || compareValues(code1, code2) || compareMessageText(d1, d2) || 0 /* EqualTo */; } function compareRelatedInformation(d1, d2) { if (!d1.relatedInformation && !d2.relatedInformation) { return 0 /* EqualTo */; } if (d1.relatedInformation && d2.relatedInformation) { - return compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || forEach(d1.relatedInformation, (d1i, index) => { + return compareValues(d2.relatedInformation.length, d1.relatedInformation.length) || forEach(d1.relatedInformation, (d1i, index) => { const d2i = d2.relatedInformation[index]; return compareDiagnostics(d1i, d2i); }) || 0 /* EqualTo */; } return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */; } -function compareMessageText(t1, t2) { - if (typeof t1 === "string" && typeof t2 === "string") { - return compareStringsCaseSensitive(t1, t2); - } else if (typeof t1 === "string") { - return -1 /* LessThan */; - } else if (typeof t2 === "string") { - return 1 /* GreaterThan */; +function compareMessageText(d1, d2) { + let headMsg1 = getDiagnosticMessage(d1); + let headMsg2 = getDiagnosticMessage(d2); + if (typeof headMsg1 !== "string") { + headMsg1 = headMsg1.messageText; + } + if (typeof headMsg2 !== "string") { + headMsg2 = headMsg2.messageText; + } + const chain1 = typeof d1.messageText !== "string" ? d1.messageText.next : void 0; + const chain2 = typeof d2.messageText !== "string" ? d2.messageText.next : void 0; + let res = compareStringsCaseSensitive(headMsg1, headMsg2); + if (res) { + return res; } - let res = compareStringsCaseSensitive(t1.messageText, t2.messageText); + res = compareMessageChain(chain1, chain2); if (res) { return res; } - if (!t1.next && !t2.next) { + if (d1.canonicalHead && !d2.canonicalHead) { + return -1 /* LessThan */; + } + if (d2.canonicalHead && !d1.canonicalHead) { + return 1 /* GreaterThan */; + } + return 0 /* EqualTo */; +} +function compareMessageChain(c1, c2) { + if (c1 === void 0 && c2 === void 0) { return 0 /* EqualTo */; } - if (!t1.next) { + if (c1 === void 0) { + return 1 /* GreaterThan */; + } + if (c2 === void 0) { return -1 /* LessThan */; } - if (!t2.next) { + return compareMessageChainSize(c1, c2) || compareMessageChainContent(c1, c2); +} +function compareMessageChainSize(c1, c2) { + if (c1 === void 0 && c2 === void 0) { + return 0 /* EqualTo */; + } + if (c1 === void 0) { return 1 /* GreaterThan */; } - const len = Math.min(t1.next.length, t2.next.length); - for (let i = 0; i < len; i++) { - res = compareMessageText(t1.next[i], t2.next[i]); + if (c2 === void 0) { + return -1 /* LessThan */; + } + let res = compareValues(c2.length, c1.length); + if (res) { + return res; + } + for (let i = 0; i < c2.length; i++) { + res = compareMessageChainSize(c1[i].next, c2[i].next); if (res) { return res; } } - if (t1.next.length < t2.next.length) { - return -1 /* LessThan */; - } else if (t1.next.length > t2.next.length) { - return 1 /* GreaterThan */; + return 0 /* EqualTo */; +} +function compareMessageChainContent(c1, c2) { + let res; + for (let i = 0; i < c2.length; i++) { + res = compareStringsCaseSensitive(c1[i].messageText, c2[i].messageText); + if (res) { + return res; + } + if (c1[i].next === void 0) { + continue; + } + res = compareMessageChainContent(c1[i].next, c2[i].next); + if (res) { + return res; + } } return 0 /* EqualTo */; } +function diagnosticsEqualityComparer(d1, d2) { + const code1 = getDiagnosticCode(d1); + const code2 = getDiagnosticCode(d2); + const msg1 = getDiagnosticMessage(d1); + const msg2 = getDiagnosticMessage(d2); + return compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) === 0 /* EqualTo */ && compareValues(d1.start, d2.start) === 0 /* EqualTo */ && compareValues(d1.length, d2.length) === 0 /* EqualTo */ && compareValues(code1, code2) === 0 /* EqualTo */ && messageTextEqualityComparer(msg1, msg2); +} +function getDiagnosticCode(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.code) || d.code; +} +function getDiagnosticMessage(d) { + var _a; + return ((_a = d.canonicalHead) == null ? void 0 : _a.messageText) || d.messageText; +} +function messageTextEqualityComparer(m1, m2) { + const t1 = typeof m1 === "string" ? m1 : m1.messageText; + const t2 = typeof m2 === "string" ? m2 : m2.messageText; + return compareStringsCaseSensitive(t1, t2) === 0 /* EqualTo */; +} function getLanguageVariant(scriptKind) { return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */; } function walkTreeForJSXTags(node) { - if (!(node.transformFlags & 2 /* ContainsJsx */)) - return void 0; + if (!(node.transformFlags & 2 /* ContainsJsx */)) return void 0; return isJsxOpeningLikeElement(node) || isJsxFragment(node) ? node : forEachChild(node, walkTreeForJSXTags); } function isFileModuleFromUsingJSXTag(file) { @@ -22028,8 +22020,7 @@ function createSymlinkCache(cwd, getCanonicalFileName) { return !!(symlinkedFiles == null ? void 0 : symlinkedFiles.size) || !!symlinkedDirectories && !!forEachEntry(symlinkedDirectories, (value) => !!value); } function processResolution(cache, resolution) { - if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) - return; + if (!resolution || !resolution.originalPath || !resolution.resolvedFileName) return; const { resolvedFileName, originalPath } = resolution; cache.setSymlinkedFile(toPath(originalPath, cwd, getCanonicalFileName), resolvedFileName); const [commonResolved, commonOriginal] = guessDirectorySymlink(resolvedFileName, originalPath, cwd, getCanonicalFileName) || emptyArray; @@ -22215,17 +22206,14 @@ function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNa return flatten(results); function visitDirectory(path2, absolutePath, depth2) { const canonicalPath = toCanonical(realpath(absolutePath)); - if (visited.has(canonicalPath)) - return; + if (visited.has(canonicalPath)) return; visited.set(canonicalPath, true); const { files, directories } = getFileSystemEntries(path2); for (const current of sort(files, compareStringsCaseSensitive)) { const name = combinePaths(path2, current); const absoluteName = combinePaths(absolutePath, current); - if (extensions && !fileExtensionIsOneOf(name, extensions)) - continue; - if (excludeRegex && excludeRegex.test(absoluteName)) - continue; + if (extensions && !fileExtensionIsOneOf(name, extensions)) continue; + if (excludeRegex && excludeRegex.test(absoluteName)) continue; if (!includeFileRegexes) { results[0].push(name); } else { @@ -22323,12 +22311,9 @@ function getSupportedExtensions(options, extraFileExtensions) { return extensions; } function getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) { - if (!options || !getResolveJsonModule(options)) - return supportedExtensions; - if (supportedExtensions === allSupportedExtensions) - return allSupportedExtensionsWithJson; - if (supportedExtensions === supportedTSExtensions) - return supportedTSExtensionsWithJson; + if (!options || !getResolveJsonModule(options)) return supportedExtensions; + if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson; + if (supportedExtensions === supportedTSExtensions) return supportedTSExtensionsWithJson; return [...supportedExtensions, [".json" /* Json */]]; } function isJSLike(scriptKind) { @@ -22413,8 +22398,7 @@ function getRequiresAtTopOfFile(sourceFile) { return requires || emptyArray; } function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) { - if (!fileName) - return false; + if (!fileName) return false; const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions); for (const extension of flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions))) { if (fileExtensionIs(fileName, extension)) { @@ -22548,7 +22532,15 @@ function rangeOfTypeParameters(sourceFile, typeParameters) { return { pos, end }; } function skipTypeChecking(sourceFile, options, host) { - return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName); + return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib || options.noCheck || host.isSourceOfProjectReferenceRedirect(sourceFile.fileName) || !canIncludeBindAndCheckDiagnsotics(sourceFile, options); +} +function canIncludeBindAndCheckDiagnsotics(sourceFile, options) { + if (!!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false) return false; + if (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */) return true; + const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; + const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); + const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); + return isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */; } function isJsonEqual(a, b) { return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && equalOwnProperties(a, b, isJsonEqual); @@ -22586,8 +22578,7 @@ function parsePseudoBigInt(stringValue) { const shiftedDigit = digit << (bitOffset & 15); segments[segment] |= shiftedDigit; const residual = shiftedDigit >>> 16; - if (residual) - segments[segment + 1] |= residual; + if (residual) segments[segment + 1] |= residual; } let base10Value = ""; let firstNonzeroSegment = segments.length - 1; @@ -22628,8 +22619,7 @@ function parseValidBigInt(text) { return { negative, base10Value }; } function isValidBigIntString(s, roundTripOnly) { - if (s === "") - return false; + if (s === "") return false; const scanner2 = createScanner( 99 /* ESNext */, /*skipTrivia*/ @@ -22666,8 +22656,7 @@ function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) { return containerKind === 264 /* InterfaceDeclaration */ || containerKind === 187 /* TypeLiteral */; } function isIdentifierInNonEmittingHeritageClause(node) { - if (node.kind !== 80 /* Identifier */) - return false; + if (node.kind !== 80 /* Identifier */) return false; const heritageClause = findAncestor(node.parent, (parent2) => { switch (parent2.kind) { case 298 /* HeritageClause */: @@ -22685,13 +22674,11 @@ function isIdentifierTypeReference(node) { return isTypeReferenceNode(node) && isIdentifier(node.typeName); } function arrayIsHomogeneous(array, comparer = equateValues) { - if (array.length < 2) - return true; + if (array.length < 2) return true; const first2 = array[0]; for (let i = 1, length2 = array.length; i < length2; i++) { const target = array[i]; - if (!comparer(first2, target)) - return false; + if (!comparer(first2, target)) return false; } return true; } @@ -22730,8 +22717,7 @@ function setEachParent(children, parent2) { return children; } function setParentRecursive(rootNode, incremental) { - if (!rootNode) - return rootNode; + if (!rootNode) return rootNode; forEachChildRecursively(rootNode, isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild); return rootNode; function bindParentToChildIgnoringJSDoc(child, parent2) { @@ -22770,14 +22756,12 @@ function expressionResultIsUnused(node) { return true; } if (isCommaListExpression(parent2)) { - if (node !== last(parent2.elements)) - return true; + if (node !== last(parent2.elements)) return true; node = parent2; continue; } if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 28 /* CommaToken */) { - if (node === parent2.left) - return true; + if (node === parent2.left) return true; node = parent2; continue; } @@ -22788,8 +22772,7 @@ function containsIgnoredPath(path) { return some(ignoredPaths, (p) => path.includes(p)); } function getContainingNodeArray(node) { - if (!node.parent) - return void 0; + if (!node.parent) return void 0; switch (node.kind) { case 168 /* TypeParameter */: const { parent: parent3 } = node; @@ -23239,13 +23222,15 @@ function createNameResolver({ let useResult = true; if (isFunctionLike(location) && lastLocation && lastLocation !== location.body) { if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 320 /* JSDoc */) { - useResult = result.flags & 262144 /* TypeParameter */ ? lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; + useResult = result.flags & 262144 /* TypeParameter */ ? !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so type parameters are accessible from them + lastLocation === location.type || lastLocation.kind === 169 /* Parameter */ || lastLocation.kind === 341 /* JSDocParameterTag */ || lastLocation.kind === 342 /* JSDocReturnTag */ || lastLocation.kind === 168 /* TypeParameter */ : false; } if (meaning & result.flags & 3 /* Variable */) { if (useOuterVariableScopeInParameter(result, location, lastLocation)) { useResult = false; } else if (result.flags & 1 /* FunctionScopedVariable */) { - useResult = lastLocation.kind === 169 /* Parameter */ || lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); + useResult = lastLocation.kind === 169 /* Parameter */ || !!(lastLocation.flags & 16 /* Synthesized */) || // Synthetic fake scopes are added for signatures so parameters are accessible from them + lastLocation === location.type && !!findAncestor(result.valueDeclaration, isParameter); } } } else if (location.kind === 194 /* ConditionalType */) { @@ -23261,8 +23246,7 @@ function createNameResolver({ withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation); switch (location.kind) { case 307 /* SourceFile */: - if (!isExternalOrCommonJsModule(location)) - break; + if (!isExternalOrCommonJsModule(location)) break; case 267 /* ModuleDeclaration */: const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; if (location.kind === 307 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { @@ -23514,8 +23498,7 @@ function createNameResolver({ if (isBindingElement(node) && node.dotDotDotToken && isObjectBindingPattern(node.parent)) { return target < 4 /* ES2017 */; } - if (isTypeNode(node)) - return false; + if (isTypeNode(node)) return false; return forEachChild(node, requiresScopeChangeWorker) || false; } } @@ -23977,30 +23960,21 @@ function createParenthesizerRules(factory2) { return factory2.createNodeArray(sameMap(types, parenthesizeElementTypeOfTupleType)); } function parenthesizeElementTypeOfTupleType(type) { - if (hasJSDocPostfixQuestion(type)) - return factory2.createParenthesizedType(type); + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); return type; } function hasJSDocPostfixQuestion(type) { - if (isJSDocNullableType(type)) - return type.postfix; - if (isNamedTupleMember(type)) - return hasJSDocPostfixQuestion(type.type); - if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) - return hasJSDocPostfixQuestion(type.type); - if (isConditionalTypeNode(type)) - return hasJSDocPostfixQuestion(type.falseType); - if (isUnionTypeNode(type)) - return hasJSDocPostfixQuestion(last(type.types)); - if (isIntersectionTypeNode(type)) - return hasJSDocPostfixQuestion(last(type.types)); - if (isInferTypeNode(type)) - return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); + if (isJSDocNullableType(type)) return type.postfix; + if (isNamedTupleMember(type)) return hasJSDocPostfixQuestion(type.type); + if (isFunctionTypeNode(type) || isConstructorTypeNode(type) || isTypeOperatorNode(type)) return hasJSDocPostfixQuestion(type.type); + if (isConditionalTypeNode(type)) return hasJSDocPostfixQuestion(type.falseType); + if (isUnionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isIntersectionTypeNode(type)) return hasJSDocPostfixQuestion(last(type.types)); + if (isInferTypeNode(type)) return !!type.typeParameter.constraint && hasJSDocPostfixQuestion(type.typeParameter.constraint); return false; } function parenthesizeTypeOfOptionalType(type) { - if (hasJSDocPostfixQuestion(type)) - return factory2.createParenthesizedType(type); + if (hasJSDocPostfixQuestion(type)) return factory2.createParenthesizedType(type); return parenthesizeNonArrayTypeOfPostfixType(type); } function parenthesizeLeadingTypeArgument(node) { @@ -24062,8 +24036,7 @@ function createNodeConverters(factory2) { convertToAssignmentElementTarget }; function convertToFunctionBlock(node, multiLine) { - if (isBlock(node)) - return node; + if (isBlock(node)) return node; const returnStatement = factory2.createReturnStatement(node); setTextRange(returnStatement, node); const body = factory2.createBlock([returnStatement], multiLine); @@ -24072,8 +24045,7 @@ function createNodeConverters(factory2) { } function convertToFunctionExpression(node) { var _a; - if (!node.body) - return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); + if (!node.body) return Debug.fail(`Cannot convert a FunctionDeclaration without a body`); const updated = factory2.createFunctionExpression( (_a = getModifiers(node)) == null ? void 0 : _a.filter((modifier) => !isExportModifier(modifier) && !isDefaultModifier(modifier)), node.asteriskToken, @@ -24922,8 +24894,7 @@ function createNodeFactory(flags, baseFactory2) { const node = createBaseDeclaration(9 /* NumericLiteral */); node.text = text; node.numericLiteralFlags = numericLiteralFlags; - if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) - node.transformFlags |= 1024 /* ContainsES2015 */; + if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) node.transformFlags |= 1024 /* ContainsES2015 */; return node; } function createBigIntLiteral(value) { @@ -24941,8 +24912,7 @@ function createNodeFactory(flags, baseFactory2) { function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) { const node = createBaseStringLiteral(text, isSingleQuote); node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape; - if (hasExtendedUnicodeEscape) - node.transformFlags |= 1024 /* ContainsES2015 */; + if (hasExtendedUnicodeEscape) node.transformFlags |= 1024 /* ContainsES2015 */; return node; } function createStringLiteralFromNode(sourceNode) { @@ -25027,8 +24997,7 @@ function createNodeFactory(flags, baseFactory2) { originalKeywordKind = void 0; } const node = createBaseIdentifier(escapeLeadingUnderscores(text)); - if (hasExtendedUnicodeEscape) - node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */; + if (hasExtendedUnicodeEscape) node.flags |= 256 /* IdentifierHasExtendedUnicodeEscape */; if (node.escapedText === "await") { node.transformFlags |= 67108864 /* ContainsPossibleTopLevelAwait */; } @@ -25039,8 +25008,7 @@ function createNodeFactory(flags, baseFactory2) { } function createTempVariable(recordTempVariable, reservedInNestedScopes, prefix, suffix) { let flags2 = 1 /* Auto */; - if (reservedInNestedScopes) - flags2 |= 8 /* ReservedInNestedScopes */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; const name = createBaseGeneratedIdentifier("", flags2, prefix, suffix); if (recordTempVariable) { recordTempVariable(name); @@ -25049,8 +25017,7 @@ function createNodeFactory(flags, baseFactory2) { } function createLoopVariable(reservedInNestedScopes) { let flags2 = 2 /* Loop */; - if (reservedInNestedScopes) - flags2 |= 8 /* ReservedInNestedScopes */; + if (reservedInNestedScopes) flags2 |= 8 /* ReservedInNestedScopes */; return createBaseGeneratedIdentifier( "", flags2, @@ -25075,8 +25042,7 @@ function createNodeFactory(flags, baseFactory2) { suffix, idText ) : `generated@${getNodeId(node)}`; - if (prefix || suffix) - flags2 |= 16 /* Optimistic */; + if (prefix || suffix) flags2 |= 16 /* Optimistic */; const name = createBaseGeneratedIdentifier(text, 4 /* Node */ | flags2, prefix, suffix); name.original = node; return name; @@ -25088,8 +25054,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createPrivateIdentifier(text) { - if (!startsWith(text, "#")) - Debug.fail("First character of private identifier must be #: " + text); + if (!startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); return createBasePrivateIdentifier(escapeLeadingUnderscores(text)); } function createBaseGeneratedPrivateIdentifier(text, autoGenerateFlags, prefix, suffix) { @@ -25104,8 +25069,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createUniquePrivateName(text, prefix, suffix) { - if (text && !startsWith(text, "#")) - Debug.fail("First character of private identifier must be #: " + text); + if (text && !startsWith(text, "#")) Debug.fail("First character of private identifier must be #: " + text); const autoGenerateFlags = 8 /* ReservedInNestedScopes */ | (text ? 3 /* Unique */ : 1 /* Auto */); return createBaseGeneratedPrivateIdentifier(text ?? "", autoGenerateFlags, prefix, suffix); } @@ -25203,36 +25167,21 @@ function createNodeFactory(flags, baseFactory2) { } function createModifiersFromModifierFlags(flags2) { const result = []; - if (flags2 & 32 /* Export */) - result.push(createModifier(95 /* ExportKeyword */)); - if (flags2 & 128 /* Ambient */) - result.push(createModifier(138 /* DeclareKeyword */)); - if (flags2 & 2048 /* Default */) - result.push(createModifier(90 /* DefaultKeyword */)); - if (flags2 & 4096 /* Const */) - result.push(createModifier(87 /* ConstKeyword */)); - if (flags2 & 1 /* Public */) - result.push(createModifier(125 /* PublicKeyword */)); - if (flags2 & 2 /* Private */) - result.push(createModifier(123 /* PrivateKeyword */)); - if (flags2 & 4 /* Protected */) - result.push(createModifier(124 /* ProtectedKeyword */)); - if (flags2 & 64 /* Abstract */) - result.push(createModifier(128 /* AbstractKeyword */)); - if (flags2 & 256 /* Static */) - result.push(createModifier(126 /* StaticKeyword */)); - if (flags2 & 16 /* Override */) - result.push(createModifier(164 /* OverrideKeyword */)); - if (flags2 & 8 /* Readonly */) - result.push(createModifier(148 /* ReadonlyKeyword */)); - if (flags2 & 512 /* Accessor */) - result.push(createModifier(129 /* AccessorKeyword */)); - if (flags2 & 1024 /* Async */) - result.push(createModifier(134 /* AsyncKeyword */)); - if (flags2 & 8192 /* In */) - result.push(createModifier(103 /* InKeyword */)); - if (flags2 & 16384 /* Out */) - result.push(createModifier(147 /* OutKeyword */)); + if (flags2 & 32 /* Export */) result.push(createModifier(95 /* ExportKeyword */)); + if (flags2 & 128 /* Ambient */) result.push(createModifier(138 /* DeclareKeyword */)); + if (flags2 & 2048 /* Default */) result.push(createModifier(90 /* DefaultKeyword */)); + if (flags2 & 4096 /* Const */) result.push(createModifier(87 /* ConstKeyword */)); + if (flags2 & 1 /* Public */) result.push(createModifier(125 /* PublicKeyword */)); + if (flags2 & 2 /* Private */) result.push(createModifier(123 /* PrivateKeyword */)); + if (flags2 & 4 /* Protected */) result.push(createModifier(124 /* ProtectedKeyword */)); + if (flags2 & 64 /* Abstract */) result.push(createModifier(128 /* AbstractKeyword */)); + if (flags2 & 256 /* Static */) result.push(createModifier(126 /* StaticKeyword */)); + if (flags2 & 16 /* Override */) result.push(createModifier(164 /* OverrideKeyword */)); + if (flags2 & 8 /* Readonly */) result.push(createModifier(148 /* ReadonlyKeyword */)); + if (flags2 & 512 /* Accessor */) result.push(createModifier(129 /* AccessorKeyword */)); + if (flags2 & 1024 /* Async */) result.push(createModifier(134 /* AsyncKeyword */)); + if (flags2 & 8192 /* In */) result.push(createModifier(103 /* InKeyword */)); + if (flags2 & 16384 /* Out */) result.push(createModifier(147 /* OutKeyword */)); return result.length ? result : void 0; } function createQualifiedName(left, right) { @@ -26589,8 +26538,7 @@ function createNodeFactory(flags, baseFactory2) { node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression); node.statement = asEmbeddedStatement(statement); node.transformFlags |= propagateChildFlags(node.awaitModifier) | propagateChildFlags(node.initializer) | propagateChildFlags(node.expression) | propagateChildFlags(node.statement) | 1024 /* ContainsES2015 */; - if (awaitModifier) - node.transformFlags |= 128 /* ContainsES2018 */; + if (awaitModifier) node.transformFlags |= 128 /* ContainsES2018 */; node.jsDoc = void 0; node.locals = void 0; node.nextContainer = void 0; @@ -27826,8 +27774,7 @@ function createNodeFactory(flags, baseFactory2) { clone2.transformFlags = node.transformFlags; setOriginal(clone2, node); const typeArguments = getIdentifierTypeArguments(node); - if (typeArguments) - setIdentifierTypeArguments(clone2, typeArguments); + if (typeArguments) setIdentifierTypeArguments(clone2, typeArguments); return clone2; } function cloneGeneratedPrivateIdentifier(node) { @@ -28200,12 +28147,9 @@ function createNodeFactory(flags, baseFactory2) { if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); - if (!allowSourceMaps) - emitFlags |= 96 /* NoSourceMap */; - if (!allowComments) - emitFlags |= 3072 /* NoComments */; - if (emitFlags) - setEmitFlags(name, emitFlags); + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(name, emitFlags); return name; } return getGeneratedNameForNode(node); @@ -28226,12 +28170,9 @@ function createNodeFactory(flags, baseFactory2) { const qualifiedName = createPropertyAccessExpression(ns, nodeIsSynthesized(name) ? name : cloneNode(name)); setTextRange(qualifiedName, name); let emitFlags = 0; - if (!allowSourceMaps) - emitFlags |= 96 /* NoSourceMap */; - if (!allowComments) - emitFlags |= 3072 /* NoComments */; - if (emitFlags) - setEmitFlags(qualifiedName, emitFlags); + if (!allowSourceMaps) emitFlags |= 96 /* NoSourceMap */; + if (!allowComments) emitFlags |= 3072 /* NoComments */; + if (emitFlags) setEmitFlags(qualifiedName, emitFlags); return qualifiedName; } function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) { @@ -28524,8 +28465,7 @@ function propagatePropertyNameFlagsOfChild(node, transformFlags) { return transformFlags | node.transformFlags & 134234112 /* PropertyNamePropagatingFlags */; } function propagateChildFlags(child) { - if (!child) - return 0 /* None */; + if (!child) return 0 /* None */; const childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind); return isNamedDeclaration(child) && isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags; } @@ -28631,8 +28571,7 @@ function setOriginalNode(node, original) { node.original = original; if (original) { const emitNode = original.emitNode; - if (emitNode) - node.emitNode = mergeEmitNode(emitNode, node.emitNode); + if (emitNode) node.emitNode = mergeEmitNode(emitNode, node.emitNode); } } return node; @@ -28653,8 +28592,7 @@ function mergeEmitNode(sourceEmitNode, destEmitNode) { classThis, assignedName } = sourceEmitNode; - if (!destEmitNode) - destEmitNode = {}; + if (!destEmitNode) destEmitNode = {}; if (flags) { destEmitNode.flags = flags; } @@ -28699,8 +28637,7 @@ function mergeEmitNode(sourceEmitNode, destEmitNode) { return destEmitNode; } function mergeTokenSourceMapRanges(sourceRanges, destRanges) { - if (!destRanges) - destRanges = []; + if (!destRanges) destRanges = []; for (const key in sourceRanges) { destRanges[key] = sourceRanges[key]; } @@ -28859,8 +28796,7 @@ function getEmitHelpers(node) { function moveEmitHelpers(source, target, predicate) { const sourceEmitNode = source.emitNode; const sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers; - if (!some(sourceEmitHelpers)) - return; + if (!some(sourceEmitHelpers)) return; const targetEmitNode = getOrCreateEmitNode(target); let helpersRemoved = 0; for (let i = 0; i < sourceEmitHelpers.length; i++) { @@ -29132,10 +29068,8 @@ function createEmitHelperFactory(context) { function createESDecorateClassElementAccessObject(name, access) { const properties = []; properties.push(createESDecorateClassElementAccessHasMethod(name)); - if (access.get) - properties.push(createESDecorateClassElementAccessGetMethod(name)); - if (access.set) - properties.push(createESDecorateClassElementAccessSetMethod(name)); + if (access.get) properties.push(createESDecorateClassElementAccessGetMethod(name)); + if (access.set) properties.push(createESDecorateClassElementAccessSetMethod(name)); return factory2.createObjectLiteralExpression(properties); } function createESDecorateClassElementContextObject(contextIn) { @@ -29468,14 +29402,10 @@ function createEmitHelperFactory(context) { } } function compareEmitHelpers(x, y) { - if (x === y) - return 0 /* EqualTo */; - if (x.priority === y.priority) - return 0 /* EqualTo */; - if (x.priority === void 0) - return 1 /* GreaterThan */; - if (y.priority === void 0) - return -1 /* LessThan */; + if (x === y) return 0 /* EqualTo */; + if (x.priority === y.priority) return 0 /* EqualTo */; + if (x.priority === void 0) return 1 /* GreaterThan */; + if (y.priority === void 0) return -1 /* LessThan */; return compareValues(x.priority, y.priority); } function helperString(input, ...args) { @@ -29919,7 +29849,7 @@ var addDisposableResourceHelper = { var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) { if (value !== null && value !== void 0) { if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose; + var dispose, inner; if (async) { if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); dispose = value[Symbol.asyncDispose]; @@ -29927,8 +29857,10 @@ var addDisposableResourceHelper = { if (dispose === void 0) { if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); dispose = value[Symbol.dispose]; + if (async) inner = dispose; } if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; env.stack.push({ value: value, dispose: dispose, async: async }); } else if (async) { @@ -30670,8 +30602,7 @@ function isSyntaxList(n) { // src/compiler/factory/nodeChildren.ts var nodeChildren = /* @__PURE__ */ new WeakMap(); function getNodeChildren(node) { - if (!isNodeKind(node.kind)) - return emptyArray; + if (!isNodeKind(node.kind)) return emptyArray; return nodeChildren.get(node); } function setNodeChildren(node, children) { @@ -31521,14 +31452,11 @@ var BinaryExpressionState; function nextState(machine, currentState) { switch (currentState) { case enter: - if (machine.onLeft) - return left; + if (machine.onLeft) return left; case left: - if (machine.onOperator) - return operator; + if (machine.onOperator) return operator; case operator: - if (machine.onRight) - return right; + if (machine.onRight) return right; case right: return exit; case exit: @@ -31594,10 +31522,8 @@ function isNonExportDefaultModifier(node) { return isModifierKind(kind) && !isExportOrDefaultKeywordKind(kind); } function elideNodes(factory2, nodes) { - if (nodes === void 0) - return void 0; - if (nodes.length === 0) - return nodes; + if (nodes === void 0) return void 0; + if (nodes.length === 0) return nodes; return setTextRange(factory2.createNodeArray([], nodes.hasTrailingComma), nodes); } function getNodeForGeneratedName(name) { @@ -31754,8 +31680,7 @@ function flattenCommaList(node) { return expressions; } function containsObjectRestOrSpread(node) { - if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) - return true; + if (node.transformFlags & 65536 /* ContainsObjectRestOrSpread */) return true; if (node.transformFlags & 128 /* ContainsES2018 */) { for (const element of getElementsOfBindingOrAssignmentPattern(node)) { const target = getTargetOfBindingOrAssignmentElement(element); @@ -31764,8 +31689,7 @@ function containsObjectRestOrSpread(node) { return true; } if (target.transformFlags & 128 /* ContainsES2018 */) { - if (containsObjectRestOrSpread(target)) - return true; + if (containsObjectRestOrSpread(target)) return true; } } } @@ -32337,8 +32261,7 @@ function forEachChildRecursively(rootNode, cbNode, cbNodes) { if (cbNodes) { const res = cbNodes(current, parent2); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } } @@ -32349,8 +32272,7 @@ function forEachChildRecursively(rootNode, cbNode, cbNodes) { } else { const res = cbNode(current, parent2); if (res) { - if (res === "skip") - continue; + if (res === "skip") continue; return res; } if (current.kind >= 166 /* FirstNode */) { @@ -32777,8 +32699,7 @@ var Parser; } Debug.assert(!node.jsDoc); const jsDoc = mapDefined(getJSDocCommentRanges(node, sourceText), (comment) => JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos)); - if (jsDoc.length) - node.jsDoc = jsDoc; + if (jsDoc.length) node.jsDoc = jsDoc; if (hasDeprecatedTag) { hasDeprecatedTag = false; node.flags |= 536870912 /* Deprecated */; @@ -32882,8 +32803,7 @@ var Parser; if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 67108864 /* ContainsPossibleTopLevelAwait */) { const oldSourceFile = sourceFile; sourceFile = reparseTopLevelAwait(sourceFile); - if (oldSourceFile !== sourceFile) - setFields(sourceFile); + if (oldSourceFile !== sourceFile) setFields(sourceFile); } return sourceFile; function setFields(sourceFile2) { @@ -33008,10 +32928,7 @@ var Parser; function parseErrorAtPosition(start, length2, message, ...args) { const lastError = lastOrUndefined(parseDiagnostics); let result; - if (message.category === 3 /* Message */ && lastError && start === lastError.start && length2 === lastError.length) { - result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); - addRelatedInfo(lastError, result); - } else if (!lastError || start !== lastError.start) { + if (!lastError || start !== lastError.start) { result = createDetachedDiagnostic(fileName, sourceText, start, length2, message, ...args); parseDiagnostics.push(result); } @@ -33274,8 +33191,7 @@ var Parser; } function parseExpectedTokenJSDoc(t) { const optional = parseOptionalTokenJSDoc(t); - if (optional) - return optional; + if (optional) return optional; Debug.assert(isKeywordOrPunctuation(t)); return createMissingNode( t, @@ -34592,8 +34508,7 @@ var Parser; } else { const type = parseTypeAnnotation(); node = factory2.createPropertySignature(modifiers, name, questionToken, type); - if (token() === 64 /* EqualsToken */) - node.initializer = parseInitializer(); + if (token() === 64 /* EqualsToken */) node.initializer = parseInitializer(); } parseTypeMemberSemicolon(); return withJSDoc(finishNode(node, pos), hasJSDoc); @@ -35963,8 +35878,7 @@ var Parser; parsingContext |= 1 << 14 /* JsxChildren */; while (true) { const child = parseJsxChild(openingTag, currentToken = scanner2.reScanJsxToken()); - if (!child) - break; + if (!child) break; list.push(child); if (isJsxOpeningElement(openingTag) && (child == null ? void 0 : child.kind) === 284 /* JsxElement */ && !tagNamesAreEquivalent(child.openingElement.tagName, child.closingElement.tagName) && tagNamesAreEquivalent(openingTag.tagName, child.closingElement.tagName)) { break; @@ -36991,8 +36905,7 @@ var Parser; } function nextTokenIsBindingIdentifierOrStartOfDestructuringOnSameLine(disallowOf) { nextToken(); - if (disallowOf && token() === 165 /* OfKeyword */) - return false; + if (disallowOf && token() === 165 /* OfKeyword */) return false; return (isBindingIdentifier() || token() === 19 /* OpenBraceToken */) && !scanner2.hasPrecedingLineBreak(); } function isUsingDeclaration() { @@ -37362,11 +37275,10 @@ var Parser; const isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */; const isAsync = modifierFlags & 1024 /* Async */ ? 2 /* Await */ : 0 /* None */; const typeParameters = parseTypeParameters(); - if (modifierFlags & 32 /* Export */) - setAwaitContext( - /*value*/ - true - ); + if (modifierFlags & 32 /* Export */) setAwaitContext( + /*value*/ + true + ); const parameters = parseParameters(isGenerator | isAsync); const type = parseReturnType( 59 /* ColonToken */, @@ -37476,8 +37388,7 @@ var Parser; const body = parseFunctionBlockOrSemicolon(flags); const node = kind === 177 /* GetAccessor */ ? factory2.createGetAccessorDeclaration(modifiers, name, parameters, type, body) : factory2.createSetAccessorDeclaration(modifiers, name, parameters, body); node.typeParameters = typeParameters; - if (isSetAccessorDeclaration(node)) - node.type = type; + if (isSetAccessorDeclaration(node)) node.type = type; return withJSDoc(finishNode(node, pos), hasJSDoc); } function isClassMemberStart() { @@ -37591,8 +37502,7 @@ var Parser; } } while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { - if (modifier.kind === 126 /* StaticKeyword */) - hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; list = append(list, modifier); hasLeadingModifier = true; } @@ -37604,8 +37514,7 @@ var Parser; } if (hasTrailingDecorator) { while (modifier = tryParseModifier(hasSeenStaticModifier, permitConstAsModifier, stopOnStartOfClassStaticBlock)) { - if (modifier.kind === 126 /* StaticKeyword */) - hasSeenStaticModifier = true; + if (modifier.kind === 126 /* StaticKeyword */) hasSeenStaticModifier = true; list = append(list, modifier); } } @@ -37720,11 +37629,10 @@ var Parser; parseExpected(86 /* ClassKeyword */); const name = parseNameOfClassDeclarationOrExpression(); const typeParameters = parseTypeParameters(); - if (some(modifiers, isExportModifier)) - setAwaitContext( - /*value*/ - true - ); + if (some(modifiers, isExportModifier)) setAwaitContext( + /*value*/ + true + ); const heritageClauses = parseHeritageClauses(); let members; if (parseExpected(19 /* OpenBraceToken */)) { @@ -38002,11 +37910,9 @@ var Parser; function parseImportClause(identifier, pos, isTypeOnly, skipJsDocLeadingAsterisks) { let namedBindings; if (!identifier || parseOptional(28 /* CommaToken */)) { - if (skipJsDocLeadingAsterisks) - scanner2.setSkipJsDocLeadingAsterisks(true); + if (skipJsDocLeadingAsterisks) scanner2.setSkipJsDocLeadingAsterisks(true); namedBindings = token() === 42 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(275 /* NamedImports */); - if (skipJsDocLeadingAsterisks) - scanner2.setSkipJsDocLeadingAsterisks(false); + if (skipJsDocLeadingAsterisks) scanner2.setSkipJsDocLeadingAsterisks(false); } return finishNode(factory2.createImportClause(isTypeOnly, identifier, namedBindings), pos); } @@ -38348,8 +38254,7 @@ var Parser; indent3 += text.length; } nextTokenJSDoc(); - while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) - ; + while (parseOptionalJsdoc(5 /* WhitespaceTrivia */)) ; if (parseOptionalJsdoc(4 /* NewLineTrivia */)) { state = 0 /* BeginningOfLine */; indent3 = 0; @@ -38359,8 +38264,7 @@ var Parser; switch (token()) { case 60 /* AtToken */: removeTrailingWhitespace(comments); - if (!commentsPos) - commentsPos = getNodePos(); + if (!commentsPos) commentsPos = getNodePos(); addTag(parseTag(indent3)); state = 0 /* BeginningOfLine */; margin = void 0; @@ -38428,8 +38332,7 @@ var Parser; if (parts.length && trimmedComments.length) { parts.push(finishNode(factory2.createJSDocText(trimmedComments), linkEnd ?? start, commentsPos)); } - if (parts.length && tags) - Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); + if (parts.length && tags) Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); } @@ -38733,8 +38636,7 @@ var Parser; skipWhitespaceOrAsterisk(); if (token() === 19 /* OpenBraceToken */ && nextTokenJSDoc() === 60 /* AtToken */ && tokenIsIdentifierOrKeyword(nextTokenJSDoc())) { const kind = scanner2.getTokenValue(); - if (isJSDocLinkTag(kind)) - return kind; + if (isJSDocLinkTag(kind)) return kind; } } function isJSDocLinkTag(kind) { @@ -39323,8 +39225,7 @@ var IncrementalParser; } IncrementalParser2.updateSourceFile = updateSourceFile2; function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) { - if (!oldDirectives) - return newDirectives; + if (!oldDirectives) return newDirectives; let commentDirectives; let addedNewlyScannedDirectives = false; for (const directive of oldDirectives) { @@ -39346,8 +39247,7 @@ var IncrementalParser; addNewlyScannedDirectives(); return commentDirectives; function addNewlyScannedDirectives() { - if (addedNewlyScannedDirectives) - return; + if (addedNewlyScannedDirectives) return; addedNewlyScannedDirectives = true; if (!commentDirectives) { commentDirectives = newDirectives; @@ -39813,8 +39713,7 @@ function extractPragmas(pragmas, range, text) { } } function addPragmaForMatch(pragmas, range, kind, match) { - if (!match) - return; + if (!match) return; const name = match[1].toLowerCase(); const pragma = commentPragmas[name]; if (!pragma || !(pragma.kind & kind)) { @@ -39822,16 +39721,13 @@ function addPragmaForMatch(pragmas, range, kind, match) { } const args = match[2]; const argument = getNamedPragmaArguments(pragma, args); - if (argument === "fail") - return; + if (argument === "fail") return; pragmas.push({ name, args: { arguments: argument, range } }); return; } function getNamedPragmaArguments(pragma, text) { - if (!text) - return {}; - if (!pragma.args) - return {}; + if (!text) return {}; + if (!pragma.args) return {}; const args = text.trim().split(/\s+/); const argMap = {}; for (let i = 0; i < pragma.args.length; i++) { @@ -40474,6 +40370,20 @@ var commandOptionsWithoutBuild = [ defaultValueDescription: false, description: Diagnostics.Disable_emitting_comments }, + { + name: "noCheck", + type: "boolean", + showInSimplifiedHelpView: false, + category: Diagnostics.Compiler_Diagnostics, + description: Diagnostics.Disable_full_type_checking_only_critical_parse_and_emit_errors_will_be_reported, + transpileOptionValue: true, + defaultValueDescription: false, + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + extraValidation() { + return [Diagnostics.Unknown_compiler_option_0, "noCheck"]; + } + }, { name: "noEmit", type: "boolean", @@ -41300,6 +41210,10 @@ var configDirTemplateSubstitutionOptions = optionDeclarations.filter( var configDirTemplateSubstitutionWatchOptions = optionsForWatch.filter( (option) => option.allowConfigDirTemplateSubstitution || !option.isCommandLineOnly && option.isFilePath ); +var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptionOfCustomType); +function isCommandLineOptionOfCustomType(option) { + return !isString(option.type); +} var optionsForBuild = [ { name: "verbose", @@ -41494,15 +41408,12 @@ function parseCommandLineWorker(diagnostics, commandLine, readFile) { const args = []; let pos = 0; while (true) { - while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) - pos++; - if (pos >= text.length) - break; + while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */) pos++; + if (pos >= text.length) break; const start = pos; if (text.charCodeAt(start) === 34 /* doubleQuote */) { pos++; - while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) - pos++; + while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */) pos++; if (pos < text.length) { args.push(text.substring(start + 1, pos)); pos++; @@ -41510,8 +41421,7 @@ function parseCommandLineWorker(diagnostics, commandLine, readFile) { errors.push(createCompilerDiagnostic(Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName)); } } else { - while (text.charCodeAt(pos) > 32 /* space */) - pos++; + while (text.charCodeAt(pos) > 32 /* space */) pos++; args.push(text.substring(start, pos)); } } @@ -41534,14 +41444,12 @@ function parseOptionValue(args, i, diagnostics, opt, options, errors) { ); i++; } else { - if (optValue === "true") - i++; + if (optValue === "true") i++; errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_false_or_null_on_command_line, opt.name)); } } else { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file_or_set_to_null_on_command_line, opt.name)); - if (optValue && !startsWith(optValue, "-")) - i++; + if (optValue && !startsWith(optValue, "-")) i++; } } else { if (!args[i] && opt.type !== "boolean") { @@ -41951,8 +41859,7 @@ function getCompilerOptionValueTypeString(option) { } function isCompilerOptionsValue(option, value) { if (option) { - if (isNullOrUndefined(value)) - return !option.disallowNullOrUndefined; + if (isNullOrUndefined(value)) return !option.disallowNullOrUndefined; if (option.type === "list") { return isArray(value); } @@ -42025,17 +41932,13 @@ function optionMapToObject(optionMap) { }; } function filterSameAsDefaultInclude(specs) { - if (!length(specs)) - return void 0; - if (length(specs) !== 1) - return specs; - if (specs[0] === defaultIncludeSpec) - return void 0; + if (!length(specs)) return void 0; + if (length(specs) !== 1) return specs; + if (specs[0] === defaultIncludeSpec) return void 0; return specs; } function matchesSpecs(path, includeSpecs, excludeSpecs, host) { - if (!includeSpecs) - return returnTrue; + if (!includeSpecs) return returnTrue; const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); @@ -42161,8 +42064,7 @@ function generateTSConfig(options, fileNames, newLine) { for (const option of optionDeclarations) { if (isAllowedOptionForOutput(option)) { let listForCategory = categorizedOptions.get(option.category); - if (!listForCategory) - categorizedOptions.set(option.category, listForCategory = []); + if (!listForCategory) categorizedOptions.set(option.category, listForCategory = []); listForCategory.push(option); } } @@ -42306,8 +42208,7 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis options.configFilePath = configFileName && normalizeSlashes(configFileName); const basePathForFileNames = normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath); const configFileSpecs = getConfigFileSpecs(); - if (sourceFile) - sourceFile.configFileSpecs = configFileSpecs; + if (sourceFile) sourceFile.configFileSpecs = configFileSpecs; setConfigFileInOptions(options, sourceFile); return { options, @@ -42346,11 +42247,11 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis const excludeOfRaw = getSpecsFromRaw("exclude"); let isDefaultIncludeSpec = false; let excludeSpecs = toPropValue(excludeOfRaw); - if (excludeOfRaw === "no-prop" && raw.compilerOptions) { - const outDir = raw.compilerOptions.outDir; - const declarationDir = raw.compilerOptions.declarationDir; + if (excludeOfRaw === "no-prop") { + const outDir = options.outDir; + const declarationDir = options.declarationDir; if (outDir || declarationDir) { - excludeSpecs = [outDir, declarationDir].filter((d) => !!d); + excludeSpecs = filter([outDir, declarationDir], (d) => !!d); } } if (filesSpecs === void 0 && includeSpecs === void 0) { @@ -42464,8 +42365,7 @@ function handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, basePath) return handleOptionConfigDirTemplateSubstitution(watchOptions, configDirTemplateSubstitutionWatchOptions, basePath); } function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, basePath) { - if (!options) - return options; + if (!options) return options; let result; for (const option of optionDeclarations2) { if (options[option.name] !== void 0) { @@ -42480,14 +42380,12 @@ function handleOptionConfigDirTemplateSubstitution(options, optionDeclarations2, case "list": Debug.assert(option.element.isFilePath); const listResult = getSubstitutedStringArrayWithConfigDirTemplate(value, basePath); - if (listResult) - setOptionValue(option, listResult); + if (listResult) setOptionValue(option, listResult); break; case "object": Debug.assert(option.name === "paths"); const objectResult = getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(value, basePath); - if (objectResult) - setOptionValue(option, objectResult); + if (objectResult) setOptionValue(option, objectResult); break; default: Debug.fail("option type not supported"); @@ -42512,12 +42410,10 @@ function getSubstitutedPathWithConfigDirTemplate(value, basePath) { return getNormalizedAbsolutePath(value.replace(configDirTemplate, "./"), basePath); } function getSubstitutedStringArrayWithConfigDirTemplate(list, basePath) { - if (!list) - return list; + if (!list) return list; let result; list.forEach((element, index) => { - if (!startsWithConfigDirTemplate(element)) - return; + if (!startsWithConfigDirTemplate(element)) return; (result ?? (result = list.slice()))[index] = getSubstitutedPathWithConfigDirTemplate(element, basePath); }); return result; @@ -42526,11 +42422,9 @@ function getSubstitutedMapLikeOfStringArrayWithConfigDirTemplate(mapLike, basePa let result; const ownKeys = getOwnKeys(mapLike); ownKeys.forEach((key) => { - if (!isArray(mapLike[key])) - return; + if (!isArray(mapLike[key])) return; const subStitution = getSubstitutedStringArrayWithConfigDirTemplate(mapLike[key], basePath); - if (!subStitution) - return; + if (!subStitution) return; (result ?? (result = assign({}, mapLike)))[key] = subStitution; }); return result; @@ -42584,16 +42478,11 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio } else { ownConfig.extendedConfigPath.forEach((extendedConfigPath) => applyExtendedConfig(result, extendedConfigPath)); } - if (result.include) - ownConfig.raw.include = result.include; - if (result.exclude) - ownConfig.raw.exclude = result.exclude; - if (result.files) - ownConfig.raw.files = result.files; - if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) - ownConfig.raw.compileOnSave = result.compileOnSave; - if (sourceFile && result.extendedSourceFiles) - sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); + if (result.include) ownConfig.raw.include = result.include; + if (result.exclude) ownConfig.raw.exclude = result.exclude; + if (result.files) ownConfig.raw.files = result.files; + if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave; + if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); ownConfig.options = assign(result.options, ownConfig.options); ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assign(result.watchOptions, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; } @@ -42604,8 +42493,7 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio const extendsRaw = extendedConfig.raw; let relativeDifference; const setPropertyInResultIfNotUndefined = (propertyName) => { - if (ownConfig.raw[propertyName]) - return; + if (ownConfig.raw[propertyName]) return; if (extendsRaw[propertyName]) { result[propertyName] = map(extendsRaw[propertyName], (path) => startsWithConfigDirTemplate(path) || isRootedDiskPath(path) ? path : combinePaths( relativeDifference || (relativeDifference = convertToRelativePath(getDirectoryPath(extendedConfigPath), basePath, createGetCanonicalFileName(host.useCaseSensitiveFileNames))), @@ -42692,19 +42580,14 @@ function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileNa } return { raw: json, options, watchOptions, typeAcquisition, extendedConfigPath }; function onPropertySet(keyText, value, propertyAssignment, parentOption, option) { - if (option && option !== extendsOptionDeclaration) - value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); + if (option && option !== extendsOptionDeclaration) value = convertJsonOption(option, value, basePath, errors, propertyAssignment, propertyAssignment.initializer, sourceFile); if (parentOption == null ? void 0 : parentOption.name) { if (option) { let currentOption; - if (parentOption === compilerOptionsDeclaration) - currentOption = options; - else if (parentOption === watchOptionsDeclaration) - currentOption = watchOptions ?? (watchOptions = {}); - else if (parentOption === typeAcquisitionDeclaration) - currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); - else - Debug.fail("Unknown option"); + if (parentOption === compilerOptionsDeclaration) currentOption = options; + else if (parentOption === watchOptionsDeclaration) currentOption = watchOptions ?? (watchOptions = {}); + else if (parentOption === typeAcquisitionDeclaration) currentOption = typeAcquisition ?? (typeAcquisition = getDefaultTypeAcquisition(configFileName)); + else Debug.fail("Unknown option"); currentOption[option.name] = value; } else if (keyText && (parentOption == null ? void 0 : parentOption.extraKeyDiagnostics)) { if (parentOption.elementOptions) { @@ -42895,17 +42778,14 @@ function normalizeNonListOptionValue(option, basePath, value) { } function validateJsonOptionValue(opt, value, errors, valueExpression, sourceFile) { var _a; - if (isNullOrUndefined(value)) - return void 0; + if (isNullOrUndefined(value)) return void 0; const d = (_a = opt.extraValidation) == null ? void 0 : _a.call(opt, value); - if (!d) - return value; + if (!d) return value; errors.push(createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, valueExpression, ...d)); return void 0; } function convertJsonOptionOfCustomType(opt, value, errors, valueExpression, sourceFile) { - if (isNullOrUndefined(value)) - return void 0; + if (isNullOrUndefined(value)) return void 0; const key = value.toLowerCase(); const val = opt.type.get(key); if (val !== void 0) { @@ -42975,14 +42855,12 @@ function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, e } function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames2, currentDirectory) { const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = spec; - if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) - return false; + if (!length(validatedIncludeSpecs) || !length(validatedExcludeSpecs)) return false; basePath = normalizePath(basePath); const keyMapper = createGetCanonicalFileName(useCaseSensitiveFileNames2); if (validatedFilesSpec) { for (const fileName of validatedFilesSpec) { - if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) - return false; + if (keyMapper(getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck) return false; } } return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath); @@ -43006,16 +42884,13 @@ function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, c function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames2, currentDirectory, basePath) { const excludePattern = getRegularExpressionForWildcard(excludeSpecs, combinePaths(normalizePath(currentDirectory), basePath), "exclude"); const excludeRegex = excludePattern && getRegexFromPattern(excludePattern, useCaseSensitiveFileNames2); - if (!excludeRegex) - return false; - if (excludeRegex.test(pathToCheck)) - return true; + if (!excludeRegex) return false; + if (excludeRegex.test(pathToCheck)) return true; return !hasExtension(pathToCheck) && excludeRegex.test(ensureTrailingDirectorySeparator(pathToCheck)); } function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) { return specs.filter((spec) => { - if (!isString(spec)) - return false; + if (!isString(spec)) return false; const diag2 = specToDiagnostic(spec, disallowTrailingRecursion); if (diag2 !== void 0) { errors.push(createDiagnostic(...diag2)); @@ -43054,8 +42929,7 @@ function getWildcardDirectories({ validatedIncludeSpecs: include, validatedExclu const existingFlags = existingPath !== void 0 ? wildcardDirectories[existingPath] : void 0; if (existingFlags === void 0 || existingFlags < flags) { wildcardDirectories[existingPath !== void 0 ? existingPath : path] = flags; - if (existingPath === void 0) - wildCardKeyToPath.set(key, path); + if (existingPath === void 0) wildCardKeyToPath.set(key, path); if (flags === 1 /* Recursive */) { recursiveKeys.push(key); } @@ -43146,8 +43020,7 @@ function convertCompilerOptionsForTelemetry(opts) { return out; } function getOptionValueWithEmptyStrings(value, option) { - if (value === void 0) - return value; + if (value === void 0) return value; switch (option.type) { case "object": return ""; @@ -43158,8 +43031,7 @@ function getOptionValueWithEmptyStrings(value, option) { case "boolean": return typeof value === "boolean" ? value : ""; case "listOrElement": - if (!isArray(value)) - return getOptionValueWithEmptyStrings(value, option.element); + if (!isArray(value)) return getOptionValueWithEmptyStrings(value, option.element); case "list": const elementType = option.element; return isArray(value) ? mapDefined(value, (v) => getOptionValueWithEmptyStrings(v, elementType)) : ""; @@ -43188,8 +43060,7 @@ function getDefaultValueForOption(option) { return {}; default: const value = firstOrUndefinedIterator(option.type.keys()); - if (value !== void 0) - return value; + if (value !== void 0) return value; return Debug.fail("Expected 'option.type' to have entries."); } } @@ -43233,26 +43104,18 @@ function removeIgnoredPackageId(r) { } function formatExtensions(extensions) { const result = []; - if (extensions & 1 /* TypeScript */) - result.push("TypeScript"); - if (extensions & 2 /* JavaScript */) - result.push("JavaScript"); - if (extensions & 4 /* Declaration */) - result.push("Declaration"); - if (extensions & 8 /* Json */) - result.push("JSON"); + if (extensions & 1 /* TypeScript */) result.push("TypeScript"); + if (extensions & 2 /* JavaScript */) result.push("JavaScript"); + if (extensions & 4 /* Declaration */) result.push("Declaration"); + if (extensions & 8 /* Json */) result.push("JSON"); return result.join(", "); } function extensionsToExtensionsArray(extensions) { const result = []; - if (extensions & 1 /* TypeScript */) - result.push(...supportedTSImplementationExtensions); - if (extensions & 2 /* JavaScript */) - result.push(...supportedJSExtensionsFlat); - if (extensions & 4 /* Declaration */) - result.push(...supportedDeclarationExtensions); - if (extensions & 8 /* Json */) - result.push(".json" /* Json */); + if (extensions & 1 /* TypeScript */) result.push(...supportedTSImplementationExtensions); + if (extensions & 2 /* JavaScript */) result.push(...supportedJSExtensionsFlat); + if (extensions & 4 /* Declaration */) result.push(...supportedDeclarationExtensions); + if (extensions & 8 /* Json */) result.push(".json" /* Json */); return result; } function resolvedTypeScriptOnly(resolved) { @@ -43265,8 +43128,7 @@ function resolvedTypeScriptOnly(resolved) { function createResolvedModuleWithFailedLookupLocationsHandlingSymlink(moduleName, resolved, isExternalLibraryImport, failedLookupLocations, affectingLocations, diagnostics, state, cache, alternateResult) { if (!state.resultFromCache && !state.compilerOptions.preserveSymlinks && resolved && isExternalLibraryImport && !resolved.originalPath && !isExternalModuleNameRelative(moduleName)) { const { resolvedFileName, originalPath } = getOriginalAndResolvedFileName(resolved.path, state.host, state.traceEnabled); - if (originalPath) - resolved = { ...resolved, path: resolvedFileName, originalPath }; + if (originalPath) resolved = { ...resolved, path: resolvedFileName, originalPath }; } return createResolvedModuleWithFailedLookupLocations( resolved, @@ -43314,18 +43176,14 @@ function initializeResolutionField(value) { return value.length ? value : void 0; } function updateResolutionField(to, value) { - if (!(value == null ? void 0 : value.length)) - return to; - if (!(to == null ? void 0 : to.length)) - return value; + if (!(value == null ? void 0 : value.length)) return to; + if (!(to == null ? void 0 : to.length)) return value; to.push(...value); return to; } function initializeResolutionFieldForReadonlyCache(fromCache, value) { - if (!(fromCache == null ? void 0 : fromCache.length)) - return initializeResolutionField(value); - if (!value.length) - return fromCache.slice(); + if (!(fromCache == null ? void 0 : fromCache.length)) return initializeResolutionField(value); + if (!value.length) return fromCache.slice(); return [...fromCache, ...value]; } function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) { @@ -43372,8 +43230,7 @@ function readPackageJsonMainField(jsonContent, baseDirectory, state) { } function readPackageJsonTypesVersionsField(jsonContent, state) { const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); - if (typesVersions === void 0) - return; + if (typesVersions === void 0) return; if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); } @@ -43381,8 +43238,7 @@ function readPackageJsonTypesVersionsField(jsonContent, state) { } function readPackageJsonTypesVersionPaths(jsonContent, state) { const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); - if (typesVersions === void 0) - return; + if (typesVersions === void 0) return; if (state.traceEnabled) { for (const key in typesVersions) { if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { @@ -43408,11 +43264,9 @@ function readPackageJsonTypesVersionPaths(jsonContent, state) { } var typeScriptVersion; function getPackageJsonTypesVersionsPaths(typesVersions) { - if (!typeScriptVersion) - typeScriptVersion = new Version(version); + if (!typeScriptVersion) typeScriptVersion = new Version(version); for (const key in typesVersions) { - if (!hasProperty(typesVersions, key)) - continue; + if (!hasProperty(typesVersions, key)) continue; const keyRange = VersionRange.tryParse(key); if (keyRange === void 0) { continue; @@ -43476,8 +43330,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil if (result) { if (traceEnabled) { trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1, typeReferenceDirectiveName, containingFile); - if (redirectedReference) - trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); + if (redirectedReference) trace(host, Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName); trace(host, Diagnostics.Resolution_for_type_reference_directive_0_was_found_in_cache_from_location_1, typeReferenceDirectiveName, containingDirectory); traceResult(result); } @@ -43539,8 +43392,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil if (resolved) { const { fileName, packageId } = resolved; let resolvedFileName = fileName, originalPath; - if (!options.preserveSymlinks) - ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); + if (!options.preserveSymlinks) ({ resolvedFileName, originalPath } = getOriginalAndResolvedFileName(fileName, host, traceEnabled)); resolvedTypeReferenceDirective = { primary, resolvedFileName, @@ -43566,8 +43418,7 @@ function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFil cache.getOrCreateCacheForNonRelativeName(typeReferenceDirectiveName, resolutionMode, redirectedReference).set(containingDirectory, result); } } - if (traceEnabled) - traceResult(result); + if (traceEnabled) traceResult(result); return result; function traceResult(result2) { var _a; @@ -43770,8 +43621,7 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { const redirectsMap = /* @__PURE__ */ new Map(); const redirectsKeyToMap = /* @__PURE__ */ new Map(); let ownMap = /* @__PURE__ */ new Map(); - if (ownOptions) - redirectsMap.set(ownOptions, ownMap); + if (ownOptions) redirectsMap.set(ownOptions, ownMap); return { getMapOfCacheRedirects, getOrCreateMapOfCacheRedirects, @@ -43795,38 +43645,30 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { } function update(newOptions) { if (ownOptions !== newOptions) { - if (ownOptions) - ownMap = getOrCreateMap( - newOptions, - /*create*/ - true - ); - else - redirectsMap.set(newOptions, ownMap); + if (ownOptions) ownMap = getOrCreateMap( + newOptions, + /*create*/ + true + ); + else redirectsMap.set(newOptions, ownMap); ownOptions = newOptions; } } function getOrCreateMap(redirectOptions, create) { let result = redirectsMap.get(redirectOptions); - if (result) - return result; + if (result) return result; const key = getRedirectsCacheKey(redirectOptions); result = redirectsKeyToMap.get(key); if (!result) { if (ownOptions) { const ownKey = getRedirectsCacheKey(ownOptions); - if (ownKey === key) - result = ownMap; - else if (!redirectsKeyToMap.has(ownKey)) - redirectsKeyToMap.set(ownKey, ownMap); - } - if (create) - result ?? (result = /* @__PURE__ */ new Map()); - if (result) - redirectsKeyToMap.set(key, result); - } - if (result) - redirectsMap.set(redirectOptions, result); + if (ownKey === key) result = ownMap; + else if (!redirectsKeyToMap.has(ownKey)) redirectsKeyToMap.set(ownKey, ownMap); + } + if (create) result ?? (result = /* @__PURE__ */ new Map()); + if (result) redirectsKeyToMap.set(key, result); + } + if (result) redirectsMap.set(redirectOptions, result); return result; } function clear2() { @@ -43836,8 +43678,7 @@ function createCacheWithRedirects(ownOptions, optionsToRedirectsKey) { optionsToRedirectsKey.clear(); redirectsKeyToMap.clear(); if (ownOptions) { - if (ownKey) - optionsToRedirectsKey.set(ownOptions, ownKey); + if (ownKey) optionsToRedirectsKey.set(ownOptions, ownKey); redirectsMap.set(ownOptions, ownMap); } } @@ -44139,8 +43980,7 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca default: return Debug.fail(`Unexpected moduleResolution: ${moduleResolution}`); } - if (result && result.resolvedModule) - (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); + if (result && result.resolvedModule) (_b = perfLogger) == null ? void 0 : _b.logInfoEvent(`Module "${moduleName}" resolved to "${result.resolvedModule.resolvedFileName}"`); (_c = perfLogger) == null ? void 0 : _c.logStopResolveModule(result && result.resolvedModule ? "" + result.resolvedModule.resolvedFileName : "null"); if (cache && !cache.isReadonly) { cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference).set(moduleName, resolutionMode, result); @@ -44164,8 +44004,7 @@ function resolveModuleName(moduleName, containingFile, compilerOptions, host, ca } function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) { const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); - if (resolved) - return resolved.value; + if (resolved) return resolved.value; if (!isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { @@ -44379,8 +44218,7 @@ function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, hos extensions = 8 /* Json */; } else if (compilerOptions.noDtsResolution) { extensions = 3 /* ImplementationFiles */; - if (getResolveJsonModule(compilerOptions)) - extensions |= 8 /* Json */; + if (getResolveJsonModule(compilerOptions)) extensions |= 8 /* Json */; } else { extensions = getResolveJsonModule(compilerOptions) ? 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */ | 8 /* Json */ : 1 /* TypeScript */ | 2 /* JavaScript */ | 4 /* Declaration */; } @@ -44881,10 +44719,8 @@ function getPeerDependenciesOfPackageJsonInfo(packageJsonInfo, state) { } function readPackageJsonPeerDependencies(packageJsonInfo, state) { const peerDependencies = readPackageJsonField(packageJsonInfo.contents.packageJsonContent, "peerDependencies", "object", state); - if (peerDependencies === void 0) - return void 0; - if (state.traceEnabled) - trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); + if (peerDependencies === void 0) return void 0; + if (state.traceEnabled) trace(state.host, Diagnostics.package_json_has_a_peerDependencies_field); const packageDirectory = realPath(packageJsonInfo.packageDirectory, state.host, state.traceEnabled); const nodeModules = packageDirectory.substring(0, packageDirectory.lastIndexOf("node_modules") + "node_modules".length) + directorySeparator; let result = ""; @@ -44899,11 +44735,9 @@ function readPackageJsonPeerDependencies(packageJsonInfo, state) { if (peerPackageJson) { const version2 = peerPackageJson.contents.packageJsonContent.version; result += `+${key}@${version2}`; - if (state.traceEnabled) - trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2); + if (state.traceEnabled) trace(state.host, Diagnostics.Found_peerDependency_0_with_1_version, key, version2); } else { - if (state.traceEnabled) - trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key); + if (state.traceEnabled) trace(state.host, Diagnostics.Failed_to_find_peerDependency_0, key); } } } @@ -44920,13 +44754,11 @@ function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { const existing = (_b = state.packageJsonInfoCache) == null ? void 0 : _b.getPackageJsonInfo(packageJsonPath); if (existing !== void 0) { if (isPackageJsonInfo(existing)) { - if (traceEnabled) - trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); + if (traceEnabled) trace(host, Diagnostics.File_0_exists_according_to_earlier_cached_lookups, packageJsonPath); (_c = state.affectingLocations) == null ? void 0 : _c.push(packageJsonPath); return existing.packageDirectory === packageDirectory ? existing : { packageDirectory, contents: existing.contents }; } else { - if (existing.directoryExists && traceEnabled) - trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); + if (existing.directoryExists && traceEnabled) trace(host, Diagnostics.File_0_does_not_exist_according_to_earlier_cached_lookups, packageJsonPath); (_d = state.failedLookupLocations) == null ? void 0 : _d.push(packageJsonPath); return void 0; } @@ -44938,16 +44770,14 @@ function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } const result = { packageDirectory, contents: { packageJsonContent, versionPaths: void 0, resolvedEntrypoints: void 0, peerDependencies: void 0 } }; - if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) - state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, result); (_e = state.affectingLocations) == null ? void 0 : _e.push(packageJsonPath); return result; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } - if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) - state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists }); + if (state.packageJsonInfoCache && !state.packageJsonInfoCache.isReadonly) state.packageJsonInfoCache.setPackageJsonInfo(packageJsonPath, { packageDirectory, directoryExists }); (_f = state.failedLookupLocations) == null ? void 0 : _f.push(packageJsonPath); } } @@ -45013,8 +44843,7 @@ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFail } } const packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state)); - if (packageFileResult) - return packageFileResult; + if (packageFileResult) return packageFileResult; if (!(state.features & 32 /* EsmMode */)) { return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state); } @@ -45180,18 +45009,12 @@ function comparePatternKeys(a, b) { const bPatternIndex = b.indexOf("*"); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - if (baseLenA > baseLenB) - return -1; - if (baseLenB > baseLenA) - return 1; - if (aPatternIndex === -1) - return 1; - if (bPatternIndex === -1) - return -1; - if (a.length > b.length) - return -1; - if (b.length > a.length) - return 1; + if (baseLenA > baseLenB) return -1; + if (baseLenB > baseLenA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; return 0; } function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { @@ -45243,11 +45066,9 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe } } function matchesPatternWithTrailer(target, name) { - if (endsWith(target, "*")) - return false; + if (endsWith(target, "*")) return false; const starPos = target.indexOf("*"); - if (starPos === -1) - return false; + if (starPos === -1) return false; return startsWith(name, target.substring(0, starPos)) && endsWith(name, target.substring(starPos + 1)); } } @@ -45331,8 +45152,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec } const finalPath = toAbsolutePath(pattern ? resolvedTarget.replace(/\*/g, subpath) : resolvedTarget + subpath); const inputLink = tryLoadInputFileForPath(finalPath, subpath, combinePaths(scope.packageDirectory, "package.json"), isImports); - if (inputLink) - return inputLink; + if (inputLink) return inputLink; return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, finalPath, @@ -45396,8 +45216,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec ); function toAbsolutePath(path) { var _a, _b; - if (path === void 0) - return path; + if (path === void 0) return path; return getNormalizedAbsolutePath(path, (_b = (_a = state.host).getCurrentDirectory) == null ? void 0 : _b.call(_a)); } function combineDirectoryPath(root, dir) { @@ -45443,8 +45262,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec if (fileExtensionIs(possibleInputBase, ext)) { const inputExts = getPossibleOriginalInputExtensionForExtension(possibleInputBase); for (const possibleExt of inputExts) { - if (!extensionIsOk(extensions, possibleExt)) - continue; + if (!extensionIsOk(extensions, possibleExt)) continue; const possibleInputWithInputExtension = changeAnyExtension(possibleInputBase, possibleExt, ext, !useCaseSensitiveFileNames(state)); if (state.host.fileExists(possibleInputWithInputExtension)) { return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( @@ -45479,13 +45297,10 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec } } function isApplicableVersionedTypesKey(conditions, key) { - if (!conditions.includes("types")) - return false; - if (!startsWith(key, "types@")) - return false; + if (!conditions.includes("types")) return false; + if (!startsWith(key, "types@")) return false; const range = VersionRange.tryParse(key.substring("types@".length)); - if (!range) - return false; + if (!range) return false; return range.test(version); } function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) { @@ -45521,8 +45336,7 @@ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, if (priorityExtensions) { traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_preferred_extensions_Colon_0, formatExtensions(priorityExtensions)); const result = lookup(priorityExtensions); - if (result) - return result; + if (result) return result; } if (secondaryExtensions && !typesScopeOnly) { traceIfEnabled(state, Diagnostics.Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0, formatExtensions(secondaryExtensions)); @@ -45767,12 +45581,10 @@ function classicNameResolver(moduleName, containingFile, compilerOptions, host, state )); }); - if (resolved2) - return resolved2; + if (resolved2) return resolved2; if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) { let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); - if (extensions & 4 /* Declaration */) - resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); + if (extensions & 4 /* Declaration */) resolved3 ?? (resolved3 = resolveFromTypeRoot(moduleName, state)); return resolved3; } } else { @@ -45788,8 +45600,7 @@ function classicNameResolver(moduleName, containingFile, compilerOptions, host, } } function resolveFromTypeRoot(moduleName, state) { - if (!state.compilerOptions.typeRoots) - return; + if (!state.compilerOptions.typeRoots) return; for (const typeRoot of state.compilerOptions.typeRoots) { const candidate = getCandidateFromTypeRoot(typeRoot, moduleName, state); const directoryExists = directoryProbablyExists(typeRoot, state.host); @@ -45808,8 +45619,7 @@ function resolveFromTypeRoot(moduleName, state) { return toSearchResult(withPackageId(packageInfo, resolvedFromFile, state)); } const resolved = loadNodeModuleFromDirectory(4 /* Declaration */, candidate, !directoryExists, state); - if (resolved) - return toSearchResult(resolved); + if (resolved) return toSearchResult(resolved); } } function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { @@ -46232,8 +46042,7 @@ function createBinder() { } if (!symbol) { symbolTable.set(name, symbol = createSymbol(0 /* None */, name)); - if (isReplaceableByMethod) - symbol.isReplaceableByMethod = true; + if (isReplaceableByMethod) symbol.isReplaceableByMethod = true; } else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) { return symbol; } else if (symbol.flags & excludes) { @@ -46309,8 +46118,7 @@ function createBinder() { ); } } else { - if (isJSDocTypeAlias(node)) - Debug.assert(isInJSFile(node)); + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); if (!isAmbientModule(node) && (hasExportModifier || container.flags & 128 /* ExportContext */)) { if (!canHaveLocals(container) || !container.locals || hasSyntacticModifier(node, 2048 /* Default */) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -46344,17 +46152,12 @@ function createBinder() { if (node.parent && isModuleDeclaration(node)) { node = node.parent; } - if (!isJSDocTypeAlias(node)) - return false; - if (!isJSDocEnumTag(node) && !!node.fullName) - return true; + if (!isJSDocTypeAlias(node)) return false; + if (!isJSDocEnumTag(node) && !!node.fullName) return true; const declName = getNameOfDeclaration(node); - if (!declName) - return false; - if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) - return true; - if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) - return true; + if (!declName) return false; + if (isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent)) return true; + if (isDeclaration(declName.parent) && getCombinedModifierFlags(declName.parent) & 32 /* Export */) return true; return false; } function bindContainer(node, containerFlags) { @@ -46407,8 +46210,7 @@ function createBinder() { node.flags &= ~5632 /* ReachabilityAndEmitFlags */; if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && nodeIsPresent(node.body)) { node.flags |= 512 /* HasImplicitReturn */; - if (hasExplicitReturn) - node.flags |= 1024 /* HasExplicitReturn */; + if (hasExplicitReturn) node.flags |= 1024 /* HasExplicitReturn */; node.endFlowNode = currentFlow; } if (node.kind === 307 /* SourceFile */) { @@ -47455,8 +47257,7 @@ function createBinder() { case 175 /* ClassStaticBlockDeclaration */: case 265 /* TypeAliasDeclaration */: case 200 /* MappedType */: - if (container.locals) - Debug.assertNode(container, canHaveLocals); + if (container.locals) Debug.assertNode(container, canHaveLocals); return declareSymbol( container.locals, /*parent*/ @@ -47826,8 +47627,7 @@ function createBinder() { return; } setParent(node, parent2); - if (tracing) - node.tracingPath = file.path; + if (tracing) node.tracingPath = file.path; const saveInStrictMode = inStrictMode; bindWorker(node); if (node.kind > 165 /* LastToken */) { @@ -47842,8 +47642,7 @@ function createBinder() { parent2 = saveParent; } else { const saveParent = parent2; - if (node.kind === 1 /* EndOfFileToken */) - parent2 = node; + if (node.kind === 1 /* EndOfFileToken */) parent2 = node; bindJSDoc(node); parent2 = saveParent; } @@ -48881,8 +48680,7 @@ function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignatu } visitedTypes[type.id] = type; const shouldBail = visitSymbol(type.symbol); - if (shouldBail) - return; + if (shouldBail) return; if (type.flags & 524288 /* Object */) { const objectType = type; const objectFlags = objectType.objectFlags; @@ -49059,10 +48857,8 @@ function getModuleSpecifierPreferences({ importModuleSpecifierPreference, import }; function getPreferredEnding(resolutionMode) { if (oldImportSpecifier !== void 0) { - if (hasJSFileExtension(oldImportSpecifier)) - return 2 /* JsExtension */; - if (endsWith(oldImportSpecifier, "/index")) - return 1 /* Index */; + if (hasJSFileExtension(oldImportSpecifier)) return 2 /* JsExtension */; + if (endsWith(oldImportSpecifier, "/index")) return 1 /* Index */; } return getModuleSpecifierEndingPreference( importModuleSpecifierEnding, @@ -49074,8 +48870,7 @@ function getModuleSpecifierPreferences({ importModuleSpecifierPreference, import } function updateModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, oldImportSpecifier, options = {}) { const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, getModuleSpecifierPreferences({}, host, compilerOptions, importingSourceFile, oldImportSpecifier), {}, options); - if (res === oldImportSpecifier) - return void 0; + if (res === oldImportSpecifier) return void 0; return res; } function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName2, host, options = {}) { @@ -49112,13 +48907,14 @@ function getModuleSpecifierWorker(compilerOptions, importingSourceFile, importin )) || getLocalModuleSpecifier(toFileName2, info, compilerOptions, host, options.overrideImportMode || getDefaultResolutionModeForFile(importingSourceFile, host, compilerOptions), preferences); } function tryGetModuleSpecifiersFromCache(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { - return tryGetModuleSpecifiersFromCacheWorker( + const result = tryGetModuleSpecifiersFromCacheWorker( moduleSymbol, importingSourceFile, host, userPreferences, options - )[0]; + ); + return result[1] && { kind: result[0], moduleSpecifiers: result[1], computedWithoutCache: false }; } function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile, host, userPreferences, options = {}) { var _a; @@ -49128,7 +48924,7 @@ function tryGetModuleSpecifiersFromCacheWorker(moduleSymbol, importingSourceFile } const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); const cached = cache == null ? void 0 : cache.get(importingSourceFile.path, moduleSourceFile.path, userPreferences, options); - return [cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache]; + return [cached == null ? void 0 : cached.kind, cached == null ? void 0 : cached.moduleSpecifiers, moduleSourceFile, cached == null ? void 0 : cached.modulePaths, cache]; } function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}) { return getModuleSpecifiersWithCacheInfo( @@ -49146,19 +48942,16 @@ function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSo function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences, options = {}, forAutoImport) { let computedWithoutCache = false; const ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker); - if (ambient) - return { moduleSpecifiers: [ambient], computedWithoutCache }; - let [specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( + if (ambient) return { kind: "ambient", moduleSpecifiers: [ambient], computedWithoutCache }; + let [kind, specifiers, moduleSourceFile, modulePaths, cache] = tryGetModuleSpecifiersFromCacheWorker( moduleSymbol, importingSourceFile, host, userPreferences, options ); - if (specifiers) - return { moduleSpecifiers: specifiers, computedWithoutCache }; - if (!moduleSourceFile) - return { moduleSpecifiers: emptyArray, computedWithoutCache }; + if (specifiers) return { kind, moduleSpecifiers: specifiers, computedWithoutCache }; + if (!moduleSourceFile) return { kind: void 0, moduleSpecifiers: emptyArray, computedWithoutCache }; computedWithoutCache = true; modulePaths || (modulePaths = getAllModulePathsWorker(getInfo(importingSourceFile.fileName, host), moduleSourceFile.originalFileName, host, compilerOptions, options)); const result = computeModuleSpecifiers( @@ -49170,8 +48963,8 @@ function getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions options, forAutoImport ); - cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, modulePaths, result); - return { moduleSpecifiers: result, computedWithoutCache }; + cache == null ? void 0 : cache.set(importingSourceFile.path, moduleSourceFile.path, userPreferences, options, result.kind, modulePaths, result.moduleSpecifiers); + return result; } function getLocalModuleSpecifierBetweenFileNames(importingFile, targetFileName, compilerOptions, host, options = {}) { const info = getInfo(importingFile.fileName, host); @@ -49191,8 +48984,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi const existingSpecifier = isFullSourceFile(importingSourceFile) && forEach(modulePaths, (modulePath) => forEach( host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), (reason) => { - if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) - return void 0; + if (reason.kind !== 3 /* Import */ || reason.file !== importingSourceFile.path) return void 0; const existingMode = host.getModeForResolutionAtIndex(importingSourceFile, reason.index); const targetMode = options.overrideImportMode ?? host.getDefaultResolutionModeForFile(importingSourceFile); if (existingMode !== targetMode && existingMode !== void 0 && targetMode !== void 0) { @@ -49203,8 +48995,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi } )); if (existingSpecifier) { - const moduleSpecifiers = [existingSpecifier]; - return moduleSpecifiers; + return { kind: void 0, moduleSpecifiers: [existingSpecifier], computedWithoutCache: true }; } const importedFileIsInNodeModules = some(modulePaths, (p) => p.isInNodeModules); let nodeModulesSpecifiers; @@ -49225,7 +49016,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi ) : void 0; nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier); if (specifier && modulePath.isRedirect) { - return nodeModulesSpecifiers; + return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; } if (!specifier) { const local = getLocalModuleSpecifier( @@ -49254,7 +49045,7 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi } } } - return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? redirectPathsSpecifiers : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers : Debug.checkDefined(relativeSpecifiers); + return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: Debug.checkDefined(relativeSpecifiers), computedWithoutCache: true }; } function getInfo(importingSourceFileName, host) { importingSourceFileName = getNormalizedAbsolutePath(importingSourceFileName, host.getCurrentDirectory()); @@ -49314,17 +49105,14 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im return isPathRelativeToParent(maybeNonRelative) || countPathComponents(relativePath) < countPathComponents(maybeNonRelative) ? relativePath : maybeNonRelative; } function packageJsonPathsAreEqual(a, b, ignoreCase) { - if (a === b) - return true; - if (a === void 0 || b === void 0) - return false; + if (a === b) return true; + if (a === void 0 || b === void 0) return false; return comparePaths(a, b, ignoreCase) === 0 /* EqualTo */; } function countPathComponents(path) { let count = 0; for (let i = startsWith(path, "./") ? 2 : 0; i < path.length; i++) { - if (path.charCodeAt(i) === 47 /* slash */) - count++; + if (path.charCodeAt(i) === 47 /* slash */) count++; } return count; } @@ -49351,15 +49139,13 @@ function forEachFileNameOfModule(importingFileName, importedFileName, host, pref let shouldFilterIgnoredPaths = !every(targets, containsIgnoredPath); if (!preferSymlinks) { const result2 = forEach(targets, (p) => !(shouldFilterIgnoredPaths && containsIgnoredPath(p)) && cb(p, referenceRedirect === p)); - if (result2) - return result2; + if (result2) return result2; } const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd); const result = symlinkedDirectories && forEachAncestorDirectory(getDirectoryPath(fullImportedFileName), (realPathDirectory) => { const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); - if (!symlinkDirectories) - return void 0; + if (!symlinkDirectories) return void 0; if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { return false; } @@ -49372,8 +49158,7 @@ function forEachFileNameOfModule(importingFileName, importedFileName, host, pref const option = resolvePath(symlinkDirectory, relative); const result2 = cb(option, target === referenceRedirect); shouldFilterIgnoredPaths = true; - if (result2) - return result2; + if (result2) return result2; } }); }); @@ -49386,8 +49171,7 @@ function getAllModulePaths(info, importedFileName, host, preferences, compilerOp const cache = (_a = host.getModuleSpecifierCache) == null ? void 0 : _a.call(host); if (cache) { const cached = cache.get(importingFilePath, importedFilePath, preferences, options); - if (cached == null ? void 0 : cached.modulePaths) - return cached.modulePaths; + if (cached == null ? void 0 : cached.modulePaths) return cached.modulePaths; } const modulePaths = getAllModulePathsWorker(info, importedFileName, host, compilerOptions, options); if (cache) { @@ -49462,8 +49246,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, sortedPaths.push(...pathsInDirectory); } const newDirectory = getDirectoryPath(directory); - if (newDirectory === directory) - break; + if (newDirectory === directory) break; directory = newDirectory; } if (allFileNames.size) { @@ -49471,8 +49254,7 @@ function getAllModulePathsWorker(info, importedFileName, host, compilerOptions, allFileNames.entries(), ([fileName, { isRedirect, isInNodeModules }]) => ({ path: fileName, isRedirect, isInNodeModules }) ); - if (remainingPaths.length > 1) - remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); + if (remainingPaths.length > 1) remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators); sortedPaths.push(...remainingPaths); } return sortedPaths; @@ -49487,20 +49269,15 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { } const ambientModuleDeclareCandidates = mapDefined(moduleSymbol.declarations, (d) => { var _a2, _b, _c, _d; - if (!isModuleDeclaration(d)) - return; + if (!isModuleDeclaration(d)) return; const topNamespace = getTopNamespace(d); - if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) - return; + if (!(((_a2 = topNamespace == null ? void 0 : topNamespace.parent) == null ? void 0 : _a2.parent) && isModuleBlock(topNamespace.parent) && isAmbientModule(topNamespace.parent.parent) && isSourceFile(topNamespace.parent.parent.parent))) return; const exportAssignment = (_d = (_c = (_b = topNamespace.parent.parent.symbol.exports) == null ? void 0 : _b.get("export=")) == null ? void 0 : _c.valueDeclaration) == null ? void 0 : _d.expression; - if (!exportAssignment) - return; + if (!exportAssignment) return; const exportSymbol = checker.getSymbolAtLocation(exportAssignment); - if (!exportSymbol) - return; + if (!exportSymbol) return; const originalExportSymbol = (exportSymbol == null ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol; - if (originalExportSymbol === d.symbol) - return topNamespace.parent.parent; + if (originalExportSymbol === d.symbol) return topNamespace.parent.parent; function getTopNamespace(namespaceDeclaration) { while (namespaceDeclaration.flags & 8 /* NestedNamespace */) { namespaceDeclaration = namespaceDeclaration.parent; @@ -49703,8 +49480,7 @@ function tryGetModuleNameFromPackageJsonImports(moduleFileName, sourceDirectory, } const conditions = getConditions(options, importMode); return (_c = forEach(getOwnKeys(imports), (k) => { - if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) - return void 0; + if (!startsWith(k, "#") || k === "#" || startsWith(k, "#/")) return void 0; const mode = endsWith(k, "/") ? 1 /* Directory */ : k.includes("*") ? 2 /* Pattern */ : 0 /* Exact */; return tryGetModuleNameFromExportsOrImports( options, @@ -49765,8 +49541,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa isPackageRootPath = true; break; } - if (!moduleFileName) - moduleFileName = moduleFileToTry; + if (!moduleFileName) moduleFileName = moduleFileToTry; packageRootIndex = path.indexOf(directorySeparator, packageRootIndex + 1); if (packageRootIndex === -1) { moduleSpecifier = processEnding(moduleFileName, allowedEndings, options, host); @@ -49843,8 +49618,7 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa } } function tryGetAnyFileFromPath(host, path) { - if (!host.fileExists) - return; + if (!host.fileExists) return; const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }])); for (const e of extensions) { const fullPath = path + e; @@ -49899,8 +49673,7 @@ function processEnding(fileName, allowedEndings, options, host) { } function tryGetRealFileNameForNonJsDeclarationFileName(fileName) { const baseName = getBaseFileName(fileName); - if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) - return void 0; + if (!endsWith(fileName, ".ts" /* Ts */) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [".d.ts" /* Dts */])) return void 0; const noExtension = removeExtension(fileName, ".ts" /* Ts */); const ext = noExtension.substring(noExtension.lastIndexOf(".")); return noExtension.substring(0, noExtension.indexOf(".d.")) + ext; @@ -50104,12 +49877,9 @@ function createTypeChecker(host) { deferredDiagnosticsCallbacks.push(arg); }; var cancellationToken; - var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); - var requestedExternalEmitHelpers; - var externalHelpersModule; var scanner2; var Symbol47 = objectAllocator.getSymbolConstructor(); - var Type28 = objectAllocator.getTypeConstructor(); + var Type29 = objectAllocator.getTypeConstructor(); var Signature14 = objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; @@ -50143,7 +49913,6 @@ function createTypeChecker(host) { var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, { isEntityNameVisible, isExpandoFunctionDeclaration, - isNonNarrowedBindableName, getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration, requiresAddingImplicitUndefined, isUndefinedIdentifierExpression(node) { @@ -50224,8 +49993,7 @@ function createTypeChecker(host) { getTypeOfSymbol, getSymbolsOfParameterPropertyDeclaration: (parameterIn, parameterName) => { const parameter = getParseTreeNode(parameterIn, isParameter); - if (parameter === void 0) - return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); + if (parameter === void 0) return Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node."); Debug.assert(isParameterPropertyDeclaration(parameter, parameter.parent)); return getSymbolsOfParameterPropertyDeclaration(parameter, escapeLeadingUnderscores(parameterName)); }, @@ -50251,6 +50019,7 @@ function createTypeChecker(host) { getBaseTypes, getBaseTypeOfLiteralType, getWidenedType, + getWidenedLiteralType, getTypeFromTypeNode: (nodeIn) => { const node = getParseTreeNode(nodeIn, isTypeNode); return node ? getTypeFromTypeNode(node) : errorType; @@ -50402,6 +50171,7 @@ function createTypeChecker(host) { getImmediateAliasedSymbol, getAliasedSymbol: resolveAlias, getEmitResolver, + requiresAddingImplicitUndefined, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule, forEachExportAndPropertyOfModule, @@ -50475,8 +50245,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ); - if (type === emptyGenericType) - return void 0; + if (type === emptyGenericType) return void 0; return type; }, isSymbolAccessible, @@ -50566,7 +50335,8 @@ function createTypeChecker(host) { getTypeOnlyAliasDeclaration, getMemberOverrideModifierStatus, isTypeParameterPossiblyReferenced, - typeHasCallOrConstructSignatures + typeHasCallOrConstructSignatures, + getSymbolFlags }; function getCandidateSignaturesForStringLiteralCompletions(call, editingArgument) { const candidatesSet = /* @__PURE__ */ new Set(); @@ -51109,8 +50879,7 @@ function createTypeChecker(host) { return key ? cachedTypes.get(key) : void 0; } function setCachedType(key, type) { - if (key) - cachedTypes.set(key, type); + if (key) cachedTypes.set(key, type); return type; } function getJsxNamespace(location) { @@ -51183,8 +50952,8 @@ function createTypeChecker(host) { void 0 ); } - function getEmitResolver(sourceFile, cancellationToken2) { - getDiagnostics2(sourceFile, cancellationToken2); + function getEmitResolver(sourceFile, cancellationToken2, skipDiagnostics) { + if (!skipDiagnostics) getDiagnostics2(sourceFile, cancellationToken2); return emitResolver; } function lookupOrIssueError(location, message, ...args) { @@ -51284,38 +51053,22 @@ function createTypeChecker(host) { } function getExcludedSymbolFlags(flags) { let result = 0; - if (flags & 2 /* BlockScopedVariable */) - result |= 111551 /* BlockScopedVariableExcludes */; - if (flags & 1 /* FunctionScopedVariable */) - result |= 111550 /* FunctionScopedVariableExcludes */; - if (flags & 4 /* Property */) - result |= 0 /* PropertyExcludes */; - if (flags & 8 /* EnumMember */) - result |= 900095 /* EnumMemberExcludes */; - if (flags & 16 /* Function */) - result |= 110991 /* FunctionExcludes */; - if (flags & 32 /* Class */) - result |= 899503 /* ClassExcludes */; - if (flags & 64 /* Interface */) - result |= 788872 /* InterfaceExcludes */; - if (flags & 256 /* RegularEnum */) - result |= 899327 /* RegularEnumExcludes */; - if (flags & 128 /* ConstEnum */) - result |= 899967 /* ConstEnumExcludes */; - if (flags & 512 /* ValueModule */) - result |= 110735 /* ValueModuleExcludes */; - if (flags & 8192 /* Method */) - result |= 103359 /* MethodExcludes */; - if (flags & 32768 /* GetAccessor */) - result |= 46015 /* GetAccessorExcludes */; - if (flags & 65536 /* SetAccessor */) - result |= 78783 /* SetAccessorExcludes */; - if (flags & 262144 /* TypeParameter */) - result |= 526824 /* TypeParameterExcludes */; - if (flags & 524288 /* TypeAlias */) - result |= 788968 /* TypeAliasExcludes */; - if (flags & 2097152 /* Alias */) - result |= 2097152 /* AliasExcludes */; + if (flags & 2 /* BlockScopedVariable */) result |= 111551 /* BlockScopedVariableExcludes */; + if (flags & 1 /* FunctionScopedVariable */) result |= 111550 /* FunctionScopedVariableExcludes */; + if (flags & 4 /* Property */) result |= 0 /* PropertyExcludes */; + if (flags & 8 /* EnumMember */) result |= 900095 /* EnumMemberExcludes */; + if (flags & 16 /* Function */) result |= 110991 /* FunctionExcludes */; + if (flags & 32 /* Class */) result |= 899503 /* ClassExcludes */; + if (flags & 64 /* Interface */) result |= 788872 /* InterfaceExcludes */; + if (flags & 256 /* RegularEnum */) result |= 899327 /* RegularEnumExcludes */; + if (flags & 128 /* ConstEnum */) result |= 899967 /* ConstEnumExcludes */; + if (flags & 512 /* ValueModule */) result |= 110735 /* ValueModuleExcludes */; + if (flags & 8192 /* Method */) result |= 103359 /* MethodExcludes */; + if (flags & 32768 /* GetAccessor */) result |= 46015 /* GetAccessorExcludes */; + if (flags & 65536 /* SetAccessor */) result |= 78783 /* SetAccessorExcludes */; + if (flags & 262144 /* TypeParameter */) result |= 526824 /* TypeParameterExcludes */; + if (flags & 524288 /* TypeAlias */) result |= 788968 /* TypeAliasExcludes */; + if (flags & 2097152 /* Alias */) result |= 2097152 /* AliasExcludes */; return result; } function recordMergedSymbol(target, source) { @@ -51329,14 +51082,10 @@ function createTypeChecker(host) { const result = createSymbol(symbol.flags, symbol.escapedName); result.declarations = symbol.declarations ? symbol.declarations.slice() : []; result.parent = symbol.parent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = new Map(symbol.members); - if (symbol.exports) - result.exports = new Map(symbol.exports); + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); recordMergedSymbol(result, symbol); return result; } @@ -51350,7 +51099,12 @@ function createTypeChecker(host) { if (resolvedTarget === unknownSymbol) { return source; } - target = cloneSymbol(resolvedTarget); + if (!(resolvedTarget.flags & getExcludedSymbolFlags(source.flags)) || (source.flags | resolvedTarget.flags) & 67108864 /* Assignment */) { + target = cloneSymbol(resolvedTarget); + } else { + reportMergeSymbolError(target, source); + return source; + } } if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; @@ -51361,13 +51115,11 @@ function createTypeChecker(host) { } addRange(target.declarations, source.declarations); if (source.members) { - if (!target.members) - target.members = createSymbolTable(); + if (!target.members) target.members = createSymbolTable(); mergeSymbolTable(target.members, source.members, unidirectional); } if (source.exports) { - if (!target.exports) - target.exports = createSymbolTable(); + if (!target.exports) target.exports = createSymbolTable(); mergeSymbolTable(target.exports, source.exports, unidirectional); } if (!unidirectional) { @@ -51382,31 +51134,30 @@ function createTypeChecker(host) { ); } } else { - const isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */); - const isEitherBlockScoped = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */); + reportMergeSymbolError(target, source); + } + return target; + function reportMergeSymbolError(target2, source2) { + const isEitherEnum = !!(target2.flags & 384 /* Enum */ || source2.flags & 384 /* Enum */); + const isEitherBlockScoped = !!(target2.flags & 2 /* BlockScopedVariable */ || source2.flags & 2 /* BlockScopedVariable */); const message = isEitherEnum ? Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations : isEitherBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; - const sourceSymbolFile = source.declarations && getSourceFileOfNode(source.declarations[0]); - const targetSymbolFile = target.declarations && getSourceFileOfNode(target.declarations[0]); + const sourceSymbolFile = source2.declarations && getSourceFileOfNode(source2.declarations[0]); + const targetSymbolFile = target2.declarations && getSourceFileOfNode(target2.declarations[0]); const isSourcePlainJs = isPlainJsFile(sourceSymbolFile, compilerOptions.checkJs); const isTargetPlainJs = isPlainJsFile(targetSymbolFile, compilerOptions.checkJs); - const symbolName2 = symbolToString(source); + const symbolName2 = symbolToString(source2); if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) { const firstFile = comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile; const secondFile = firstFile === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile; const filesDuplicates = getOrUpdate(amalgamatedDuplicates, `${firstFile.path}|${secondFile.path}`, () => ({ firstFile, secondFile, conflictingSymbols: /* @__PURE__ */ new Map() })); const conflictingSymbolInfo = getOrUpdate(filesDuplicates.conflictingSymbols, symbolName2, () => ({ isBlockScoped: isEitherBlockScoped, firstFileLocations: [], secondFileLocations: [] })); - if (!isSourcePlainJs) - addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source); - if (!isTargetPlainJs) - addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target); + if (!isSourcePlainJs) addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source2); + if (!isTargetPlainJs) addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target2); } else { - if (!isSourcePlainJs) - addDuplicateDeclarationErrorsForSymbols(source, message, symbolName2, target); - if (!isTargetPlainJs) - addDuplicateDeclarationErrorsForSymbols(target, message, symbolName2, source); + if (!isSourcePlainJs) addDuplicateDeclarationErrorsForSymbols(source2, message, symbolName2, target2); + if (!isTargetPlainJs) addDuplicateDeclarationErrorsForSymbols(target2, message, symbolName2, source2); } } - return target; function addDuplicateLocations(locs, symbol) { if (symbol.declarations) { for (const decl of symbol.declarations) { @@ -51433,21 +51184,17 @@ function createTypeChecker(host) { /*isPrototypeAssignment*/ false ) ? getNameOfExpando(relatedNode) : getNameOfDeclaration(relatedNode)) || relatedNode; - if (adjustedNode === errorNode) - continue; + if (adjustedNode === errorNode) continue; err.relatedInformation = err.relatedInformation || []; const leadingMessage = createDiagnosticForNode(adjustedNode, Diagnostics._0_was_also_declared_here, symbolName2); const followOnMessage = createDiagnosticForNode(adjustedNode, Diagnostics.and_here); - if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) - continue; + if (length(err.relatedInformation) >= 5 || some(err.relatedInformation, (r) => compareDiagnostics(r, followOnMessage) === 0 /* EqualTo */ || compareDiagnostics(r, leadingMessage) === 0 /* EqualTo */)) continue; addRelatedInfo(err, !length(err.relatedInformation) ? leadingMessage : followOnMessage); } } function combineSymbolTables(first2, second) { - if (!(first2 == null ? void 0 : first2.size)) - return second; - if (!(second == null ? void 0 : second.size)) - return first2; + if (!(first2 == null ? void 0 : first2.size)) return second; + if (!(second == null ? void 0 : second.size)) return first2; const combined = createSymbolTable(); mergeSymbolTable(combined, first2); mergeSymbolTable(combined, second); @@ -51523,8 +51270,7 @@ function createTypeChecker(host) { } } function getSymbolLinks(symbol) { - if (symbol.flags & 33554432 /* Transient */) - return symbol.links; + if (symbol.flags & 33554432 /* Transient */) return symbol.links; const id = getSymbolId(symbol); return symbolLinks[id] ?? (symbolLinks[id] = new SymbolLinks()); } @@ -51536,7 +51282,6 @@ function createTypeChecker(host) { if (meaning) { const symbol = getMergedSymbol(symbols.get(name)); if (symbol) { - Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -51756,6 +51501,7 @@ function createTypeChecker(host) { ); const message = meaning === 1920 /* Namespace */ || nameArg && typeof nameArg !== "string" && nodeIsSynthesized(nameArg) ? Diagnostics.Cannot_find_namespace_0_Did_you_mean_1 : isUncheckedJS ? Diagnostics.Could_not_find_name_0_Did_you_mean_1 : Diagnostics.Cannot_find_name_0_Did_you_mean_1; const diagnostic = createError(errorLocation, message, diagnosticName(nameArg), suggestionName); + diagnostic.canonicalHead = getCanonicalDiagnostic(nameNotFoundMessage, diagnosticName(nameArg)); addErrorOrSuggestion(!isUncheckedJS, diagnostic); if (suggestion.valueDeclaration) { addRelatedInfo( @@ -51823,8 +51569,7 @@ function createTypeChecker(host) { }); } function addTypeOnlyDeclarationRelatedInfo(diagnostic, typeOnlyDeclaration, unescapedName) { - if (!typeOnlyDeclaration) - return diagnostic; + if (!typeOnlyDeclaration) return diagnostic; return addRelatedInfo( diagnostic, createDiagnosticForNode( @@ -52073,8 +51818,7 @@ function createTypeChecker(host) { const declaration = (_a = result.declarations) == null ? void 0 : _a.find( (d) => isBlockOrCatchScoped(d) || isClassLike(d) || d.kind === 266 /* EnumDeclaration */ ); - if (declaration === void 0) - return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); + if (declaration === void 0) return Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration"); if (!(declaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) { let diagnosticMessage; const declarationName = declarationNameToString(getNameOfDeclaration(declaration)); @@ -52398,12 +52142,9 @@ function createTypeChecker(host) { Debug.assert(valueSymbol.declarations || typeSymbol.declarations); result.declarations = deduplicate(concatenate(valueSymbol.declarations, typeSymbol.declarations), equateValues); result.parent = valueSymbol.parent || typeSymbol.parent; - if (valueSymbol.valueDeclaration) - result.valueDeclaration = valueSymbol.valueDeclaration; - if (typeSymbol.members) - result.members = new Map(typeSymbol.members); - if (valueSymbol.exports) - result.exports = new Map(valueSymbol.exports); + if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; + if (typeSymbol.members) result.members = new Map(typeSymbol.members); + if (valueSymbol.exports) result.exports = new Map(valueSymbol.exports); return result; } function getExportOfModule(symbol, name, specifier, dontResolveAlias) { @@ -52684,8 +52425,7 @@ function createTypeChecker(host) { } } function isNonLocalAlias(symbol, excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */) { - if (!symbol) - return false; + if (!symbol) return false; return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */); } function resolveSymbol(symbol, dontResolveAlias) { @@ -52697,8 +52437,7 @@ function createTypeChecker(host) { if (!links.aliasTarget) { links.aliasTarget = resolvingSymbol; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); const target = getTargetOfAliasDeclaration(node); if (links.aliasTarget === resolvingSymbol) { links.aliasTarget = target || unknownSymbol; @@ -52753,8 +52492,7 @@ function createTypeChecker(host) { return flags; } function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty, exportStarDeclaration, exportStarName) { - if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) - return false; + if (!aliasDeclaration || isPropertyAccessExpression(aliasDeclaration)) return false; const sourceSymbol = getSymbolOfDeclaration(aliasDeclaration); if (isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) { const links2 = getSymbolLinks(sourceSymbol); @@ -52782,10 +52520,22 @@ function createTypeChecker(host) { return !!aliasDeclarationLinks.typeOnlyDeclaration; } function getTypeOnlyAliasDeclaration(symbol, include) { + var _a; if (!(symbol.flags & 2097152 /* Alias */)) { return void 0; } const links = getSymbolLinks(symbol); + if (links.typeOnlyDeclaration === void 0) { + links.typeOnlyDeclaration = false; + const resolved = resolveSymbol(symbol); + markSymbolOfAliasDeclarationIfTypeOnly( + (_a = symbol.declarations) == null ? void 0 : _a[0], + getDeclarationOfAliasSymbol(symbol) && getImmediateAliasedSymbol(symbol), + resolved, + /*overwriteEmpty*/ + true + ); + } if (include === void 0) { return links.typeOnlyDeclaration || void 0; } @@ -52795,44 +52545,6 @@ function createTypeChecker(host) { } return void 0; } - function markExportAsReferenced(node) { - if (!canCollectSymbolAliasAccessabilityData) { - return; - } - const symbol = getSymbolOfDeclaration(node); - const target = resolveAlias(symbol); - if (target) { - const markAlias = target === unknownSymbol || getSymbolFlags( - symbol, - /*excludeTypeOnlyMeanings*/ - true - ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); - if (markAlias) { - markAliasSymbolAsReferenced(symbol); - } - } - } - function markAliasSymbolAsReferenced(symbol) { - Debug.assert(canCollectSymbolAliasAccessabilityData); - const links = getSymbolLinks(symbol); - if (!links.referenced) { - links.referenced = true; - const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); - if (isInternalModuleImportEqualsDeclaration(node)) { - if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { - checkExpressionCached(node.moduleReference); - } - } - } - } - function markConstEnumAliasAsReferenced(symbol) { - const links = getSymbolLinks(symbol); - if (!links.constEnumReferenced) { - links.constEnumReferenced = true; - } - } function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) { if (entityName.kind === 80 /* Identifier */ && isRightSideOfQualifiedNameOrPropertyAccess(entityName)) { entityName = entityName.parent; @@ -52985,7 +52697,6 @@ function createTypeChecker(host) { } else { Debug.assertNever(name, "Unknown entity name kind."); } - Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (!nodeIsSynthesized(name) && isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 277 /* ExportAssignment */)) { markSymbolOfAliasDeclarationIfTypeOnly( getAliasDeclarationFromName(name), @@ -53314,8 +53025,7 @@ function createTypeChecker(host) { merged.exports = createSymbolTable(); } moduleSymbol.exports.forEach((s, name) => { - if (name === "export=" /* ExportEquals */) - return; + if (name === "export=" /* ExportEquals */) return; merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s); }); if (merged === exported) { @@ -53369,14 +53079,10 @@ function createTypeChecker(host) { result.parent = symbol.parent; result.links.target = symbol; result.links.originatingImport = referenceParent; - if (symbol.valueDeclaration) - result.valueDeclaration = symbol.valueDeclaration; - if (symbol.constEnumOnlyModule) - result.constEnumOnlyModule = true; - if (symbol.members) - result.members = new Map(symbol.members); - if (symbol.exports) - result.exports = new Map(symbol.exports); + if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true; + if (symbol.members) result.members = new Map(symbol.members); + if (symbol.exports) result.exports = new Map(symbol.exports); const resolvedModuleType = resolveStructuredTypeMembers(moduleType); result.links.type = createAnonymousType(result, resolvedModuleType.members, emptyArray, emptyArray, resolvedModuleType.indexInfos); return result; @@ -53450,11 +53156,9 @@ function createTypeChecker(host) { return links.resolvedExports; } function extendExportSymbols(target, source, lookupTable, exportNode) { - if (!source) - return; + if (!source) return; source.forEach((sourceSymbol, id) => { - if (id === "default" /* Default */) - return; + if (id === "default" /* Default */) return; const targetSymbol = target.get(id); if (!targetSymbol) { target.set(id, sourceSymbol); @@ -53564,19 +53268,16 @@ function createTypeChecker(host) { } if (containingFile && containingFile.imports) { for (const importRef of containingFile.imports) { - if (nodeIsSynthesized(importRef)) - continue; + if (nodeIsSynthesized(importRef)) continue; const resolvedModule = resolveExternalModuleName( enclosingDeclaration, importRef, /*ignoreErrors*/ true ); - if (!resolvedModule) - continue; + if (!resolvedModule) continue; const ref = getAliasForSymbolInContainer(resolvedModule, symbol); - if (!ref) - continue; + if (!ref) continue; results = append(results, resolvedModule); } if (length(results)) { @@ -53589,12 +53290,10 @@ function createTypeChecker(host) { } const otherFiles = host.getSourceFiles(); for (const file of otherFiles) { - if (!isExternalModule(file)) - continue; + if (!isExternalModule(file)) continue; const sym = getSymbolOfDeclaration(file); const ref = getAliasForSymbolInContainer(sym, symbol); - if (!ref) - continue; + if (!ref) continue; results = append(results, sym); } return links.extendedContainers = results || emptyArray; @@ -53707,7 +53406,7 @@ function createTypeChecker(host) { } function createType(flags) { var _a; - const result = new Type28(checker, flags); + const result = new Type29(checker, flags); typeCount++; result.id = typeCount; (_a = tracing) == null ? void 0 : _a.recordType(result); @@ -53719,7 +53418,7 @@ function createTypeChecker(host) { return result; } function createOriginType(flags) { - return new Type28(checker, flags); + return new Type29(checker, flags); } function createIntrinsicType(kind, intrinsicName, objectFlags = 0 /* None */, debugIntrinsicName) { checkIntrinsicName(intrinsicName, debugIntrinsicName); @@ -53779,21 +53478,17 @@ function createTypeChecker(host) { resolved.callSignatures = callSignatures; resolved.constructSignatures = constructSignatures; resolved.indexInfos = indexInfos; - if (members !== emptySymbols) - resolved.properties = getNamedMembers(members); + if (members !== emptySymbols) resolved.properties = getNamedMembers(members); return resolved; } function createAnonymousType(symbol, members, callSignatures, constructSignatures, indexInfos) { return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, indexInfos); } function getResolvedTypeWithoutAbstractConstructSignatures(type) { - if (type.constructSignatures.length === 0) - return type; - if (type.objectTypeWithoutAbstractConstructSignatures) - return type.objectTypeWithoutAbstractConstructSignatures; + if (type.constructSignatures.length === 0) return type; + if (type.objectTypeWithoutAbstractConstructSignatures) return type.objectTypeWithoutAbstractConstructSignatures; const constructSignatures = filter(type.constructSignatures, (signature) => !(signature.flags & 4 /* Abstract */)); - if (type.constructSignatures === constructSignatures) - return type; + if (type.constructSignatures === constructSignatures) return type; const typeCopy = createAnonymousType( type.symbol, type.members, @@ -54028,8 +53723,7 @@ function createTypeChecker(host) { return access.accessibility === 0 /* Accessible */; } function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) { - if (!length(symbols)) - return; + if (!length(symbols)) return; let hadAccessibleChain; let earlyModuleBail = false; for (const symbol of symbols) { @@ -54207,7 +53901,14 @@ function createTypeChecker(host) { ).accessibility === 0 /* Accessible */) { return { accessibility: 0 /* Accessible */ }; } - return symbol && hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || { + if (!symbol) { + return { + accessibility: 3 /* NotResolved */, + errorSymbolName: getTextOfNode(firstIdentifier), + errorNode: firstIdentifier + }; + } + return hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) || { accessibility: 1 /* NotAccessible */, errorSymbolName: getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -54271,8 +53972,7 @@ function createTypeChecker(host) { function typeToString(type, enclosingDeclaration, flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */, writer = createTextWriter("")) { const noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */; const typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0)); - if (typeNode === void 0) - return Debug.fail("should always get typenode"); + if (typeNode === void 0) return Debug.fail("should always get typenode"); const printer = type !== unresolvedType ? createPrinterWithRemoveComments() : createPrinterWithDefaults(); const sourceFile = enclosingDeclaration && getSourceFileOfNode(enclosingDeclaration); printer.writeNode( @@ -54315,38 +54015,48 @@ function createTypeChecker(host) { function isClassInstanceSide(type) { return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(type.flags & 524288 /* Object */) && !!(getObjectFlags(type) & 16777216 /* IsClassInstanceClone */)); } + function getTypeFromTypeNodeWithoutContext(node) { + return getTypeFromTypeNode(node); + } function createNodeBuilder() { return { - typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typeToTypeNodeHelper(type, context)), - typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), - expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)), - serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)), - serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => serializeReturnTypeForSignature(context, signature)), - indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( + typeToTypeNode: (type, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeToTypeNodeHelper(type, context)), + typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), + expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)), + serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)), + serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => serializeReturnTypeForSignature(context, signature)), + indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( indexInfo, context, /*typeNode*/ void 0 )), - signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)), - symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToName( + signatureToSignatureDeclaration: (signature, kind, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => signatureToSignatureDeclarationHelper(signature, kind, context)), + symbolToEntityName: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToName( symbol, context, meaning, /*expectsIdentifier*/ false )), - symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToExpression(symbol, context, meaning)), - symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)), - symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToParameterDeclaration(symbol, context)), - typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => typeParameterToDeclaration(parameter, context)), - symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), - symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext(enclosingDeclaration, flags, tracker, (context) => symbolToNode(symbol, context, meaning)) + symbolToExpression: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToExpression(symbol, context, meaning)), + symbolToTypeParameterDeclarations: (symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeParametersToTypeParameterDeclarations(symbol, context)), + symbolToParameterDeclaration: (symbol, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToParameterDeclaration(symbol, context)), + typeParameterToDeclaration: (parameter, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => typeParameterToDeclaration(parameter, context)), + symbolTableToDeclarationStatements: (symbolTable, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolTableToDeclarationStatements(symbolTable, context)), + symbolToNode: (symbol, meaning, enclosingDeclaration, flags, tracker) => withContext2(enclosingDeclaration, flags, tracker, (context) => symbolToNode(symbol, context, meaning)) }; + function getTypeFromTypeNode2(context, node, noMappedTypes) { + const type = getTypeFromTypeNodeWithoutContext(node); + if (!context.mapper) return type; + const mappedType = instantiateType(type, context.mapper); + return noMappedTypes && mappedType !== type ? void 0 : mappedType; + } function setTextRange2(context, range, location) { - if (!nodeIsSynthesized(range) && !(range.flags & 16 /* Synthesized */) && (!context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(range))) { + if (!nodeIsSynthesized(range) || !(range.flags & 16 /* Synthesized */) || !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(getOriginalNode(range))) { range = factory.cloneNode(range); } + if (range === location) return range; if (!location) { return range; } @@ -54387,7 +54097,7 @@ function createTypeChecker(host) { } const clone2 = tryReuseExistingNonParameterTypeNode(context, typeNode, type, host2); if (clone2) { - if (addUndefined && !someType(getTypeFromTypeNode(typeNode), (t) => !!(t.flags & 32768 /* Undefined */))) { + if (addUndefined && !someType(getTypeFromTypeNode2(context, typeNode), (t) => !!(t.flags & 32768 /* Undefined */))) { return factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } return clone2; @@ -54400,8 +54110,13 @@ function createTypeChecker(host) { } return void 0; } - function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType) { - if (typeNodeIsEquivalentToType(existing, host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { + function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + )) { + if (annotationType && typeNodeIsEquivalentToType(host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { const result = tryReuseExistingTypeNodeHelper(context, existing); if (result) { return result; @@ -54413,8 +54128,7 @@ function createTypeChecker(host) { if (context.flags & 1073741824 /* WriteComputedProps */) { if (symbol.valueDeclaration) { const name = getNameOfDeclaration(symbol.valueDeclaration); - if (name && isComputedPropertyName(name)) - return name; + if (name && isComputedPropertyName(name)) return name; } const nameType = getSymbolLinks(symbol).nameType; if (nameType && nameType.flags & (1024 /* EnumLiteral */ | 8192 /* UniqueESSymbol */)) { @@ -54424,8 +54138,7 @@ function createTypeChecker(host) { } return symbolToExpression(symbol, context, meaning); } - function withContext(enclosingDeclaration, flags, tracker, cb) { - Debug.assert(enclosingDeclaration === void 0 || (enclosingDeclaration.flags & 16 /* Synthesized */) === 0); + function withContext2(enclosingDeclaration, flags, tracker, cb) { const moduleResolverHost = (tracker == null ? void 0 : tracker.trackSymbol) ? tracker.moduleResolverHost : flags & 134217728 /* DoNotIncludeSymbolChain */ ? createBasicNodeBuilderModuleSpecifierResolutionHost(host) : void 0; const context = { enclosingDeclaration, @@ -54439,7 +54152,19 @@ function createTypeChecker(host) { inferTypeParameters: void 0, approximateLength: 0, trackedSymbols: void 0, - bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)) + bundled: !!compilerOptions.outFile && !!enclosingDeclaration && isExternalOrCommonJsModule(getSourceFileOfNode(enclosingDeclaration)), + truncating: false, + usedSymbolNames: void 0, + remappedSymbolNames: void 0, + remappedSymbolReferences: void 0, + reverseMappedStack: void 0, + mustCreateTypeParameterSymbolList: true, + typeParameterSymbolList: void 0, + mustCreateTypeParametersNamesLookups: true, + typeParameterNames: void 0, + typeParameterNamesByText: void 0, + typeParameterNamesByTextNextNameCount: void 0, + mapper: void 0 }; context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); const resultingNode = cb(context); @@ -54449,8 +54174,7 @@ function createTypeChecker(host) { return context.encounteredError ? void 0 : resultingNode; } function checkTruncationLength(context) { - if (context.truncating) - return context.truncating; + if (context.truncating) return context.truncating; return context.truncating = context.approximateLength > (context.flags & 1 /* NoTruncation */ ? noTruncationMaximumTruncationLength : defaultMaximumTruncationLength); } function typeToTypeNodeHelper(type, context) { @@ -54601,8 +54325,7 @@ function createTypeChecker(host) { } if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) { const typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context); - if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) - return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes); + if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */)) return factory.createTypeReferenceNode(factory.createIdentifier(""), typeArgumentNodes); if (length(typeArgumentNodes) === 1 && type.aliasSymbol === globalArrayType.symbol) { return factory.createArrayTypeNode(typeArgumentNodes[0]); } @@ -54732,8 +54455,8 @@ function createTypeChecker(host) { context.inferTypeParameters = type2.root.inferTypeParameters; const extendsTypeNode2 = typeToTypeNodeHelper(instantiateType(type2.root.extendsType, newMapper), context); context.inferTypeParameters = saveInferTypeParameters2; - const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.trueType), newMapper)); - const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode(type2.root.node.falseType), newMapper)); + const trueTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.trueType), newMapper)); + const falseTypeNode2 = typeToTypeNodeOrCircularityElision(instantiateType(getTypeFromTypeNode2(context, type2.root.node.falseType), newMapper)); return factory.createConditionalTypeNode( checkTypeNode, factory.createInferTypeNode(factory.createTypeParameterDeclaration( @@ -54816,7 +54539,7 @@ function createTypeChecker(host) { context.approximateLength += 10; const result = setEmitFlags(mappedTypeNode, 1 /* SingleLine */); if (isHomomorphicMappedTypeWithNonHomomorphicInstantiation(type2) && context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { - const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode(type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); + const originalConstraint = instantiateType(getConstraintOfTypeParameter(getTypeFromTypeNode2(context, type2.declaration.typeParameter.constraint.type)) || unknownType, type2.mapper); return factory.createConditionalTypeNode( typeToTypeNodeHelper(getModifiersTypeFromMappedType(type2), context), factory.createInferTypeNode(factory.createTypeParameterDeclaration( @@ -55182,8 +54905,7 @@ function createTypeChecker(host) { typeElements.push(signatureToSignatureDeclarationHelper(signature, 179 /* CallSignature */, context)); } for (const signature of resolvedType.constructSignatures) { - if (signature.flags & 4 /* Abstract */) - continue; + if (signature.flags & 4 /* Abstract */) continue; typeElements.push(signatureToSignatureDeclarationHelper(signature, 180 /* ConstructSignature */, context)); } for (const info of resolvedType.indexInfos) { @@ -55270,7 +54992,8 @@ function createTypeChecker(host) { const getterDeclaration = getDeclarationOfKind(propertySymbol, 177 /* GetAccessor */); const getterSignature = getSignatureFromDeclaration(getterDeclaration); typeElements.push( - setCommentRange( + setCommentRange2( + context, signatureToSignatureDeclarationHelper(getterSignature, 177 /* GetAccessor */, context, { name: propertyName }), getterDeclaration ) @@ -55278,7 +55001,8 @@ function createTypeChecker(host) { const setterDeclaration = getDeclarationOfKind(propertySymbol, 178 /* SetAccessor */); const setterSignature = getSignatureFromDeclaration(setterDeclaration); typeElements.push( - setCommentRange( + setCommentRange2( + context, signatureToSignatureDeclarationHelper(setterSignature, 178 /* SetAccessor */, context, { name: propertyName }), setterDeclaration ) @@ -55336,11 +55060,17 @@ function createTypeChecker(host) { setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } } else if (propertySymbol.valueDeclaration) { - setCommentRange(node, propertySymbol.valueDeclaration); + setCommentRange2(context, node, propertySymbol.valueDeclaration); } return node; } } + function setCommentRange2(context, node, range) { + if (context.enclosingFile && context.enclosingFile === getSourceFileOfNode(range)) { + return setCommentRange(node, range); + } + return node; + } function mapToTypeNodes(types, context, isBareList) { if (some(types)) { if (checkTruncationLength(context)) { @@ -55437,22 +55167,22 @@ function createTypeChecker(host) { } function signatureToSignatureDeclarationHelper(signature, kind, context, options) { var _a; - const flags = context.flags; - context.flags &= ~256 /* SuppressAnyReturnType */; - context.approximateLength += 3; let typeParameters; let typeArguments; - if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { - typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); - } else { - typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); - } const expandedParams = getExpandedParameters( signature, /*skipUnionExpanding*/ true )[0]; - const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters); + const cleanup = enterNewScope(context, signature.declaration, expandedParams, signature.typeParameters, signature.parameters, signature.mapper); + context.approximateLength += 3; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map((parameter) => typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context)); + } else { + typeParameters = signature.typeParameters && signature.typeParameters.map((parameter) => typeParameterToDeclaration(parameter, context)); + } + const flags = context.flags; + context.flags &= ~256 /* SuppressAnyReturnType */; const parameters = (some(expandedParams, (p) => p !== expandedParams[expandedParams.length - 1] && !!(getCheckFlags(p) & 32768 /* RestParameter */)) ? signature.parameters : expandedParams).map((parameter) => symbolToParameterDeclaration(parameter, context, kind === 176 /* Constructor */)); const thisParameter = context.flags & 33554432 /* OmitThisParameter */ ? void 0 : tryGetThisParameterDeclaration(signature, context); if (thisParameter) { @@ -55550,15 +55280,18 @@ function createTypeChecker(host) { return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).typeParameters : isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))]; } function getParametersInScope(node) { - return isFunctionLike(node) || isJSDocSignature(node) ? getExpandedParameters( - getSignatureFromDeclaration(node), - /*skipUnionExpanding*/ - true - )[0] : void 0; - } - function enterNewScope(context, declaration, expandedParams, typeParameters) { - let cleanup; - if (context.enclosingDeclaration && declaration && declaration !== context.enclosingDeclaration && !isInJSFile(declaration) && (some(expandedParams) || some(typeParameters))) { + return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).parameters : void 0; + } + function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) { + const cleanupContext = cloneNodeBuilderContext(context); + let cleanupParams; + let cleanupTypeParams; + const oldEnclosingDecl = context.enclosingDeclaration; + const oldMapper = context.mapper; + if (mapper) { + context.mapper = mapper; + } + if (context.enclosingDeclaration && declaration) { let pushFakeScope2 = function(kind, addAll) { Debug.assert(context.enclosingDeclaration); let existingFakeScope; @@ -55570,40 +55303,45 @@ function createTypeChecker(host) { Debug.assertOptionalNode(existingFakeScope, isBlock); const locals = (existingFakeScope == null ? void 0 : existingFakeScope.locals) ?? createSymbolTable(); let newLocals; + let oldLocals; addAll((name, symbol) => { - if (!locals.has(name)) { - newLocals = append(newLocals, name); - locals.set(name, symbol); + if (existingFakeScope) { + const oldSymbol = locals.get(name); + if (!oldSymbol) { + newLocals = append(newLocals, name); + } else { + oldLocals = append(oldLocals, { name, oldSymbol }); + } } + locals.set(name, symbol); }); - if (!newLocals) - return; - const oldCleanup = cleanup; - function undo() { - forEach(newLocals, (s) => locals.delete(s)); - oldCleanup == null ? void 0 : oldCleanup(); - } - if (existingFakeScope) { - cleanup = undo; - } else { - const fakeScope = parseNodeFactory.createBlock(emptyArray); + if (!existingFakeScope) { + const fakeScope = factory.createBlock(emptyArray); getNodeLinks(fakeScope).fakeScopeForSignatureDeclaration = kind; fakeScope.locals = locals; - const saveEnclosingDeclaration = context.enclosingDeclaration; - setParent(fakeScope, saveEnclosingDeclaration); + setParent(fakeScope, context.enclosingDeclaration); context.enclosingDeclaration = fakeScope; - cleanup = () => { - context.enclosingDeclaration = saveEnclosingDeclaration; - undo(); + } else { + return function undo() { + forEach(newLocals, (s) => locals.delete(s)); + forEach(oldLocals, (s) => locals.set(s.name, s.oldSymbol)); }; } }; var pushFakeScope = pushFakeScope2; - pushFakeScope2( + cleanupParams = !some(expandedParams) ? void 0 : pushFakeScope2( "params", (add) => { - for (const param of expandedParams ?? emptyArray) { - if (!forEach(param.declarations, (d) => { + if (!expandedParams) return; + for (let pIndex = 0; pIndex < expandedParams.length; pIndex++) { + const param = expandedParams[pIndex]; + const originalParam = originalParameters == null ? void 0 : originalParameters[pIndex]; + if (originalParameters && originalParam !== param) { + add(param.escapedName, unknownSymbol); + if (originalParam) { + add(originalParam.escapedName, unknownSymbol); + } + } else if (!forEach(param.declarations, (d) => { if (isParameter(d) && isBindingPattern(d.name)) { bindPattern(d.name); return true; @@ -55634,8 +55372,8 @@ function createTypeChecker(host) { } } ); - if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { - pushFakeScope2( + if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && some(typeParameters)) { + cleanupTypeParams = pushFakeScope2( "typeParams", (add) => { for (const typeParam of typeParameters ?? emptyArray) { @@ -55645,8 +55383,14 @@ function createTypeChecker(host) { } ); } - return cleanup; } + return () => { + cleanupParams == null ? void 0 : cleanupParams(); + cleanupTypeParams == null ? void 0 : cleanupTypeParams(); + cleanupContext(); + context.enclosingDeclaration = oldEnclosingDecl; + context.mapper = oldMapper; + }; } function tryGetThisParameterDeclaration(signature, context) { if (signature.thisParameter) { @@ -55663,7 +55407,7 @@ function createTypeChecker(host) { "this", /*questionToken*/ void 0, - typeToTypeNodeHelper(getTypeFromTypeNode(thisTag.typeExpression), context) + typeToTypeNodeHelper(getTypeFromTypeNode2(context, thisTag.typeExpression), context) ); } } @@ -55678,8 +55422,11 @@ function createTypeChecker(host) { context.flags = savedContextFlags; return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); } + function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) { + return typeNode && tryReuseExistingNonParameterTypeNode(context, typeNode, type) || typeToTypeNodeHelper(type, context); + } function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) { - const constraintNode = constraint && typeToTypeNodeHelper(constraint, context); + const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context); return typeParameterToDeclarationWithConstraint(type, context, constraintNode); } function typePredicateToTypePredicateNodeHelper(typePredicate, context) { @@ -55754,8 +55501,7 @@ function createTypeChecker(host) { } } function trackComputedName(accessExpression, enclosingDeclaration, context) { - if (!context.tracker.canTrackSymbol) - return; + if (!context.tracker.canTrackSymbol) return; const firstIdentifier = getFirstIdentifier(accessExpression); const name = resolveName( firstIdentifier, @@ -55865,7 +55611,11 @@ function createTypeChecker(host) { if ((_a = context.typeParameterSymbolList) == null ? void 0 : _a.has(symbolId)) { return void 0; } - (context.typeParameterSymbolList || (context.typeParameterSymbolList = /* @__PURE__ */ new Set())).add(symbolId); + if (context.mustCreateTypeParameterSymbolList) { + context.mustCreateTypeParameterSymbolList = false; + context.typeParameterSymbolList = new Set(context.typeParameterSymbolList); + } + context.typeParameterSymbolList.add(symbolId); let typeParameterNodes; if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < chain.length - 1) { const parentSymbol = symbol; @@ -56068,8 +55818,7 @@ function createTypeChecker(host) { } } const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; if (index > stopper) { const LHS = createAccessFromSymbolChain(chain2, index - 1, stopper); @@ -56097,7 +55846,7 @@ function createTypeChecker(host) { return false; } function typeParameterToName(type, context) { - var _a, _b; + var _a, _b, _c, _d; if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) { const cached = context.typeParameterNames.get(getTypeId(type)); if (cached) { @@ -56114,11 +55863,15 @@ function createTypeChecker(host) { if (!(result.kind & 80 /* Identifier */)) { return factory.createIdentifier("(Missing type parameter)"); } + const decl = (_b = (_a = type.symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0]; + if (decl && isTypeParameterDeclaration(decl)) { + result = setTextRange2(context, result, decl.name); + } if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) { const rawtext = result.escapedText; - let i = ((_a = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _a.get(rawtext)) || 0; + let i = ((_c = context.typeParameterNamesByTextNextNameCount) == null ? void 0 : _c.get(rawtext)) || 0; let text = rawtext; - while (((_b = context.typeParameterNamesByText) == null ? void 0 : _b.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) { + while (((_d = context.typeParameterNamesByText) == null ? void 0 : _d.has(text)) || typeParameterShadowsOtherTypeParameterInScope(text, context, type)) { i++; text = `${rawtext}_${i}`; } @@ -56127,9 +55880,15 @@ function createTypeChecker(host) { result = factory.createIdentifier(text); setIdentifierTypeArguments(result, typeArguments); } - (context.typeParameterNamesByTextNextNameCount || (context.typeParameterNamesByTextNextNameCount = /* @__PURE__ */ new Map())).set(rawtext, i); - (context.typeParameterNames || (context.typeParameterNames = /* @__PURE__ */ new Map())).set(getTypeId(type), result); - (context.typeParameterNamesByText || (context.typeParameterNamesByText = /* @__PURE__ */ new Set())).add(text); + if (context.mustCreateTypeParametersNamesLookups) { + context.mustCreateTypeParametersNamesLookups = false; + context.typeParameterNames = new Map(context.typeParameterNames); + context.typeParameterNamesByTextNextNameCount = new Map(context.typeParameterNamesByTextNextNameCount); + context.typeParameterNamesByText = new Set(context.typeParameterNamesByText); + } + context.typeParameterNamesByTextNextNameCount.set(rawtext, i); + context.typeParameterNames.set(getTypeId(type), result); + context.typeParameterNamesByText.add(text); } return result; } @@ -56150,8 +55909,7 @@ function createTypeChecker(host) { context.flags ^= 16777216 /* InInitialEntityName */; } const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createQualifiedName(createEntityNameFromSymbolChain(chain2, index - 1), identifier) : identifier; } @@ -56175,8 +55933,7 @@ function createTypeChecker(host) { } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; return index > 0 ? factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain2, index - 1), identifier) : identifier; } else { @@ -56192,8 +55949,7 @@ function createTypeChecker(host) { } if (!expression) { const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); - if (typeParameterNodes) - setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); + if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; expression = identifier; } @@ -56254,35 +56010,33 @@ function createTypeChecker(host) { } } function cloneNodeBuilderContext(context) { - const initial = { ...context }; - if (initial.typeParameterNames) { - initial.typeParameterNames = new Map(initial.typeParameterNames); - } - if (initial.typeParameterNamesByText) { - initial.typeParameterNamesByText = new Set(initial.typeParameterNamesByText); - } - if (initial.typeParameterSymbolList) { - initial.typeParameterSymbolList = new Set(initial.typeParameterSymbolList); - } - if (initial.typeParameterNamesByTextNextNameCount) { - initial.typeParameterNamesByTextNextNameCount = new Map(initial.typeParameterNamesByTextNextNameCount); - } - initial.tracker = new SymbolTrackerImpl(initial, initial.tracker.inner, initial.tracker.moduleResolverHost); - return initial; + const oldMustCreateTypeParameterSymbolList = context.mustCreateTypeParameterSymbolList; + const oldMustCreateTypeParametersNamesLookups = context.mustCreateTypeParametersNamesLookups; + context.mustCreateTypeParameterSymbolList = true; + context.mustCreateTypeParametersNamesLookups = true; + const oldTypeParameterNames = context.typeParameterNames; + const oldTypeParameterNamesByText = context.typeParameterNamesByText; + const oldTypeParameterNamesByTextNextNameCount = context.typeParameterNamesByTextNextNameCount; + const oldTypeParameterSymbolList = context.typeParameterSymbolList; + return () => { + context.typeParameterNames = oldTypeParameterNames; + context.typeParameterNamesByText = oldTypeParameterNamesByText; + context.typeParameterNamesByTextNextNameCount = oldTypeParameterNamesByTextNextNameCount; + context.typeParameterSymbolList = oldTypeParameterSymbolList; + context.mustCreateTypeParameterSymbolList = oldMustCreateTypeParameterSymbolList; + context.mustCreateTypeParametersNamesLookups = oldMustCreateTypeParametersNamesLookups; + }; } function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) { return symbol.declarations && find(symbol.declarations, (s) => !!getNonlocalEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!findAncestor(s, (n) => n === enclosingDeclaration))); } function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) { - if (!(getObjectFlags(type) & 4 /* Reference */)) - return true; - if (!isTypeReferenceNode(existing)) - return true; + if (!(getObjectFlags(type) & 4 /* Reference */)) return true; + if (!isTypeReferenceNode(existing)) return true; void getTypeFromTypeReference(existing); const symbol = getNodeLinks(existing).resolvedSymbol; const existingTarget = symbol && getDeclaredTypeOfSymbol(symbol); - if (!existingTarget || existingTarget !== type.target) - return true; + if (!existingTarget || existingTarget !== type.target) return true; return length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters); } function getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration) { @@ -56295,31 +56049,32 @@ function createTypeChecker(host) { var _a; const addUndefined = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration); const enclosingDeclaration = context.enclosingDeclaration; - if (!isErrorType(type) && enclosingDeclaration) { - const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol, getEnclosingDeclarationIgnoringFakeScope(enclosingDeclaration)); + const oldFlags = context.flags; + if (declaration && hasInferredType(declaration) && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { + syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, context); + } + context.flags |= -2147483648 /* NoSyntacticPrinter */; + if (enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */)) { + const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol); if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) { const existing = getNonlocalEffectiveTypeAnnotationNode(declWithExistingAnnotation); - const result2 = tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); + const result2 = !isTypePredicateNode(existing) && tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); if (result2) { + context.flags = oldFlags; return result2; } } } - const oldFlags = context.flags; if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) { context.flags |= 1048576 /* AllowUniqueESSymbolType */; } const decl = declaration ?? symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); const expr = decl && isDeclarationWithPossibleInnerTypeNodeReuse(decl) ? getPossibleTypeNodeReuseExpression(decl) : void 0; - if (decl && hasInferredType(decl) && !(context.flags & -2147483648 /* NoSyntacticPrinter */)) { - syntacticNodeBuilder.serializeTypeOfDeclaration(decl, context); - } - context.flags |= -2147483648 /* NoSyntacticPrinter */; const result = expressionOrTypeToTypeNode(context, expr, type, addUndefined); context.flags = oldFlags; return result; } - function typeNodeIsEquivalentToType(typeNode, annotatedDeclaration, type, typeFromTypeNode = getTypeFromTypeNode(typeNode)) { + function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) { if (typeFromTypeNode === type) { return true; } @@ -56331,8 +56086,7 @@ function createTypeChecker(host) { function serializeReturnTypeForSignature(context, signature) { const suppressAny = context.flags & 256 /* SuppressAnyReturnType */; const flags = context.flags; - if (suppressAny) - context.flags &= ~256 /* SuppressAnyReturnType */; + if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; let returnTypeNode; const returnType = getReturnTypeOfSignature(signature); if (returnType && !(suppressAny && isTypeAny(returnType))) { @@ -56350,13 +56104,10 @@ function createTypeChecker(host) { function serializeReturnTypeForSignatureWorker(context, signature) { const typePredicate = getTypePredicateOfSignature(signature); const type = getReturnTypeOfSignature(signature); - if (!isErrorType(type) && context.enclosingDeclaration) { + if (context.enclosingDeclaration && (!isErrorType(type) || context.flags & 1 /* AllowUnresolvedNames */) && signature.declaration && !nodeIsSynthesized(signature.declaration)) { const annotation = signature.declaration && getNonlocalEffectiveReturnTypeAnnotationNode(signature.declaration); - const enclosingDeclarationIgnoringFakeScope = getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); - if (!!findAncestor(annotation, (n) => n === enclosingDeclarationIgnoringFakeScope) && annotation) { - const annotated = getTypeFromTypeNode(annotation); - const thisInstantiated = annotated.flags & 262144 /* TypeParameter */ && annotated.isThisType ? instantiateType(annotated, signature.mapper) : annotated; - const result = tryReuseExistingNonParameterTypeNode(context, annotation, type, signature.declaration, thisInstantiated); + if (annotation && getTypeFromTypeNode2(context, annotation) === type) { + const result = tryReuseExistingTypeNodeHelper(context, annotation); if (result) { return result; } @@ -56405,13 +56156,37 @@ function createTypeChecker(host) { /*dontResolveAlias*/ true ); + if (context.enclosingDeclaration && !(sym && sym.flags & 262144 /* TypeParameter */)) { + sym = getExportSymbolOfValueSymbolIfExported(sym); + const symAtLocation = resolveEntityName( + leftmost, + meaning, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + context.enclosingDeclaration + ); + if ( + // Check for unusable parameters symbols + symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node + symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it shoudl point to the same reference + symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym) + ) { + if (symAtLocation !== unknownSymbol) { + context.tracker.reportInferenceFallback(node); + } + introducesError = true; + return { introducesError, node, sym }; + } + } if (sym) { if (sym.flags & 1 /* FunctionScopedVariable */ && sym.valueDeclaration) { - if (isPartOfParameterDeclaration(sym.valueDeclaration)) { + if (isPartOfParameterDeclaration(sym.valueDeclaration) || isJSDocParameterTag(sym.valueDeclaration)) { return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; } } - if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the curent context if they are are resolvable + if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable !isDeclarationName(node) && isSymbolAccessible( sym, context.enclosingDeclaration, @@ -56419,6 +56194,7 @@ function createTypeChecker(host) { /*shouldComputeAliasesToMakeVisible*/ false ).accessibility !== 0 /* Accessible */) { + context.tracker.reportInferenceFallback(node); introducesError = true; } else { context.tracker.trackSymbol(sym, context.enclosingDeclaration, meaning); @@ -56445,33 +56221,209 @@ function createTypeChecker(host) { return updated; } } + function serializeTypeName(context, node, isTypeOf, typeArguments) { + const meaning = isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const symbol = resolveEntityName( + node, + meaning, + /*ignoreErrors*/ + true + ); + if (!symbol) return void 0; + const resolvedSymbol = symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol; + if (isSymbolAccessible( + symbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility !== 0 /* Accessible */) return void 0; + return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments); + } + function canReuseTypeNode(context, existing) { + if (isInJSFile(existing)) { + if (isLiteralImportTypeNode(existing)) { + void getTypeFromImportTypeNode(existing); + const nodeSymbol = getNodeLinks(existing).resolvedSymbol; + return !nodeSymbol || !// The import type resolved using jsdoc fallback logic + (!existing.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic + !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol)))); + } + } + if (isThisTypeNode(existing)) { + if (context.mapper === void 0) return true; + const type = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + ); + return !!type; + } + if (isTypeReferenceNode(existing)) { + if (isConstTypeReference(existing)) return false; + const type = getTypeFromTypeReference(existing); + const symbol = getNodeLinks(existing).resolvedSymbol; + if (!symbol) return false; + if (symbol.flags & 262144 /* TypeParameter */) { + const type2 = getDeclaredTypeOfSymbol(symbol); + if (context.mapper && getMappedType(type2, context.mapper) !== type2) { + return false; + } + } + if (isInJSDoc(existing)) { + return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && symbol.flags & 788968 /* Type */; + } + } + if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) { + const effectiveEnclosingContext = context.enclosingDeclaration && getEnclosingDeclarationIgnoringFakeScope(context.enclosingDeclaration); + return !!findAncestor(existing, (n) => n === effectiveEnclosingContext); + } + return true; + } + function serializeExistingTypeNode(context, typeNode) { + const type = getTypeFromTypeNode2(context, typeNode); + return typeToTypeNodeHelper(type, context); + } function tryReuseExistingTypeNodeHelper(context, existing) { if (cancellationToken && cancellationToken.throwIfCancellationRequested) { cancellationToken.throwIfCancellationRequested(); } let hadError = false; + const { finalizeBoundary, startRecoveryScope } = createRecoveryBoundary(); const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode); - if (hadError) { + if (!finalizeBoundary()) { return void 0; } + context.approximateLength += existing.end - existing.pos; return transformed; function visitExistingNodeTreeSymbols(node) { + if (hadError) return node; + const recover = startRecoveryScope(); const onExitNewScope = isNewScopeNode(node) ? onEnterNewScope(node) : void 0; const result = visitExistingNodeTreeSymbolsWorker(node); onExitNewScope == null ? void 0 : onExitNewScope(); - return result === node ? setTextRange2(context, factory.cloneNode(result), node) : result; + if (hadError) { + if (isTypeNode(node) && !isTypePredicateNode(node)) { + recover(); + return serializeExistingTypeNode(context, node); + } + return node; + } + return result ? setTextRange2(context, result, node) : void 0; + } + function createRecoveryBoundary() { + let unreportedErrors; + const oldTracker = context.tracker; + const oldTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = []; + const oldEncounteredError = context.encounteredError; + context.tracker = new SymbolTrackerImpl(context, { + ...oldTracker.inner, + reportCyclicStructureError() { + markError(() => oldTracker.reportCyclicStructureError()); + }, + reportInaccessibleThisError() { + markError(() => oldTracker.reportInaccessibleThisError()); + }, + reportInaccessibleUniqueSymbolError() { + markError(() => oldTracker.reportInaccessibleUniqueSymbolError()); + }, + reportLikelyUnsafeImportRequiredError(specifier) { + markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier)); + }, + reportNonSerializableProperty(name) { + markError(() => oldTracker.reportNonSerializableProperty(name)); + }, + trackSymbol(sym, decl, meaning) { + const accessibility = isSymbolAccessible( + sym, + decl, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ); + if (accessibility.accessibility !== 0 /* Accessible */) { + (context.trackedSymbols ?? (context.trackedSymbols = [])).push([sym, decl, meaning]); + return true; + } + return false; + }, + moduleResolverHost: context.tracker.moduleResolverHost + }, context.tracker.moduleResolverHost); + return { + startRecoveryScope: startRecoveryScope2, + finalizeBoundary: finalizeBoundary2 + }; + function markError(unreportedError) { + hadError = true; + (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError); + } + function startRecoveryScope2() { + var _a; + const initialTrackedSymbolsTop = ((_a = context.trackedSymbols) == null ? void 0 : _a.length) ?? 0; + const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0; + return () => { + hadError = false; + if (context.trackedSymbols) { + context.trackedSymbols.length = initialTrackedSymbolsTop; + } + if (unreportedErrors) { + unreportedErrors.length = unreportedErrorsTop; + } + }; + } + function finalizeBoundary2() { + context.tracker = oldTracker; + const newTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = oldTrackedSymbols; + context.encounteredError = oldEncounteredError; + unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn()); + if (hadError) { + return false; + } + newTrackedSymbols == null ? void 0 : newTrackedSymbols.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); + return true; + } } function onEnterNewScope(node) { - const oldContex = context; - context = cloneNodeBuilderContext(context); - const cleanup = enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node)); - return onExitNewScope; - function onExitNewScope() { - cleanup == null ? void 0 : cleanup(); - context = oldContex; + return enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node)); + } + function tryVisitTypeReference(node) { + if (canReuseTypeNode(context, node)) { + const { introducesError, node: newName } = trackExistingEntityName(node.typeName, context); + const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode); + if (!introducesError) { + const updated = factory.updateTypeReferenceNode( + node, + newName, + typeArguments + ); + return setTextRange2(context, updated, node); + } else { + const serializedName = serializeTypeName( + context, + node.typeName, + /*isTypeOf*/ + false, + typeArguments + ); + if (serializedName) { + return setTextRange2(context, serializedName, node.typeName); + } + } } } function visitExistingNodeTreeSymbolsWorker(node) { + if (isJSDocTypeExpression(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode); + } if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) { return factory.createKeywordTypeNode(133 /* AnyKeyword */); } @@ -56493,8 +56445,8 @@ function createTypeChecker(host) { if (isJSDocTypeLiteral(node)) { return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { const name = isIdentifier(t.name) ? t.name : t.name.right; - const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText); - const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; + const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, node), name.escapedText); + const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode2(context, t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; return factory.createPropertySignature( /*modifiers*/ void 0, @@ -56535,7 +56487,7 @@ function createTypeChecker(host) { /*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), + setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ @@ -56550,7 +56502,7 @@ function createTypeChecker(host) { /*modifiers*/ void 0, getEffectiveDotDotDotForParameter(p), - getNameForJSDocFunctionParameter(p, i), + setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), p.questionToken, visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), /*initializer*/ @@ -56560,20 +56512,44 @@ function createTypeChecker(host) { ); } } - if (isTypeReferenceNode(node) && isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName( - node, - 788968 /* Type */, - /*ignoreErrors*/ - true - ))) { - return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); + if (isThisTypeNode(node)) { + if (canReuseTypeNode(context, node)) { + return node; + } + hadError = true; + return node; + } + if (isTypeParameterDeclaration(node)) { + return factory.updateTypeParameterDeclaration( + node, + node.modifiers, + setTextRange2(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node), + visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode), + visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + if (isIndexedAccessTypeNode(node) && isTypeReferenceNode(node.objectType)) { + const objectType = tryVisitTypeReference(node.objectType); + if (!objectType) { + hadError = true; + return node; + } + return factory.updateIndexedAccessTypeNode(node, objectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTypeReferenceNode(node)) { + const result = tryVisitTypeReference(node); + if (result) { + return result; + } + hadError = true; + return node; } if (isLiteralImportTypeNode(node)) { const nodeSymbol = getNodeLinks(node).resolvedSymbol; if (isInJSDoc(node) && nodeSymbol && // The import type resolved using jsdoc fallback logic (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic !(length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { - return setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node); + return setTextRange2(context, typeToTypeNodeHelper(getTypeFromTypeNode2(context, node), context), node); } return factory.updateImportTypeNode( node, @@ -56585,15 +56561,12 @@ function createTypeChecker(host) { ); } if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !isLateBindableName(node.name)) { - return void 0; + if (!(context.flags & 1 /* AllowUnresolvedNames */ && hasDynamicName(node) && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */)) { + return void 0; + } } if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) { - let visited = visitEachChild( - node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 - ); + let visited = visitEachChild2(node, visitExistingNodeTreeSymbols); if (visited === node) { visited = setTextRange2(context, factory.cloneNode(node), node); } @@ -56603,21 +56576,58 @@ function createTypeChecker(host) { } return visited; } - if (isEntityName(node) || isEntityNameExpression(node)) { - if (isDeclarationName(node)) { + if (isTypeQueryNode(node)) { + const { introducesError, node: exprName } = trackExistingEntityName(node.exprName, context); + if (introducesError) { + const serializedName = serializeTypeName( + context, + node.exprName, + /*isTypeOf*/ + true + ); + if (serializedName) { + return setTextRange2(context, serializedName, node.exprName); + } + hadError = true; return node; } - const { introducesError, node: result } = trackExistingEntityName(node, context); - hadError = hadError || introducesError; - return result; - } - if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { - const visited = visitEachChild( + return factory.updateTypeQueryNode( node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 + exprName, + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode) ); + } + if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) { + const { node: result, introducesError } = trackExistingEntityName(node.expression, context); + if (!introducesError) { + return factory.updateComputedPropertyName(node, result); + } else { + const type = getWidenedType(getRegularTypeOfExpression(node.expression)); + const computedPropertyNameType = typeToTypeNodeHelper(type, context); + Debug.assertNode(computedPropertyNameType, isLiteralTypeNode); + const literal = computedPropertyNameType.literal; + if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(compilerOptions))) { + return factory.createIdentifier(literal.text); + } + if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) { + return literal; + } + return factory.updateComputedPropertyName(node, literal); + } + } + if (isTypePredicateNode(node)) { + let parameterName; + if (isIdentifier(node.parameterName)) { + const { node: result, introducesError } = trackExistingEntityName(node.parameterName, context); + hadError = hadError || introducesError; + parameterName = result; + } else { + parameterName = node.parameterName; + } + return factory.updateTypePredicateNode(node, node.assertsModifier, parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { + const visited = visitEachChild2(node, visitExistingNodeTreeSymbols); const clone2 = setTextRange2(context, visited === node ? factory.cloneNode(node) : visited, node); const flags = getEmitFlags(clone2); setEmitFlags(clone2, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */)); @@ -56643,12 +56653,46 @@ function createTypeChecker(host) { falseType2 ); } - return visitEachChild( - node, - visitExistingNodeTreeSymbols, - /*context*/ - void 0 - ); + if (isTypeOperatorNode(node)) { + if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) { + if (!canReuseTypeNode(context, node)) { + hadError = true; + return node; + } + } else if (node.operator === 143 /* KeyOfKeyword */) { + if (isTypeReferenceNode(node.type)) { + const type = tryVisitTypeReference(node.type); + if (!type) { + hadError = true; + return node; + } + return factory.updateTypeOperatorNode(node, type); + } + } + } + return visitEachChild2(node, visitExistingNodeTreeSymbols); + function visitEachChild2(node2, visitor) { + const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2); + return visitEachChild( + node2, + visitor, + /*context*/ + void 0, + nonlocalNode ? visitNodesWithoutCopyingPositions : void 0 + ); + } + function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) { + let result = visitNodes2(nodes, visitor, test, start, count); + if (result) { + if (result.pos !== -1 || result.end !== -1) { + if (result === nodes) { + result = factory.createNodeArray(nodes, nodes.hasTrailingComma); + } + setTextRangePosEnd(result, -1, -1); + } + } + return result; + } function getEffectiveDotDotDotForParameter(p) { return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); } @@ -56657,13 +56701,39 @@ function createTypeChecker(host) { } function rewriteModuleSpecifier(parent2, lit) { if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) { - const targetFile = getExternalModuleFileFromDeclaration(parent2); - if (targetFile) { - const newName = getSpecifierForModuleSymbol(targetFile.symbol, context); - if (newName !== lit.text) { - return setOriginalNode(factory.createStringLiteral(newName), lit); + let name = lit.text; + const nodeSymbol = getNodeLinks(node).resolvedSymbol; + const meaning = parent2.isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const parentSymbol = nodeSymbol && isSymbolAccessible( + nodeSymbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility === 0 /* Accessible */ && lookupSymbolChain( + nodeSymbol, + context, + meaning, + /*yieldModuleSymbol*/ + true + )[0]; + if (parentSymbol && parentSymbol.flags & 1536 /* Module */) { + name = getSpecifierForModuleSymbol(parentSymbol, context); + } else { + const targetFile = getExternalModuleFileFromDeclaration(parent2); + if (targetFile) { + name = getSpecifierForModuleSymbol(targetFile.symbol, context); } } + if (name.includes("/node_modules/")) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(name); + } + } + if (name !== lit.text) { + return setOriginalNode(factory.createStringLiteral(name), lit); + } } return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral); } @@ -56699,8 +56769,7 @@ function createTypeChecker(host) { ...oldcontext.tracker.inner, trackSymbol: (sym, decl, meaning) => { var _a2, _b; - if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) - return false; + if ((_a2 = context.remappedSymbolNames) == null ? void 0 : _a2.has(getSymbolId(sym))) return false; const accessibleResult = isSymbolAccessible( sym, decl, @@ -56910,6 +56979,7 @@ function createTypeChecker(host) { } } function serializeSymbol(symbol, isPrivate, propertyAsAlias) { + void getPropertiesOfType(getTypeOfSymbol(symbol)); const visitedSym = getMergedSymbol(symbol); if (visitedSymbols.has(getSymbolId(visitedSym))) { return; @@ -56917,19 +56987,9 @@ function createTypeChecker(host) { visitedSymbols.add(getSymbolId(visitedSym)); const skipMembershipCheck = !isPrivate; if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) { - const oldContext = context; - context = cloneNodeBuilderContext(context); + const scopeCleanup = cloneNodeBuilderContext(context); serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); - if (context.reportedDiagnostic) { - oldcontext.reportedDiagnostic = context.reportedDiagnostic; - } - if (context.trackedSymbols) { - if (!oldContext.trackedSymbols) - oldContext.trackedSymbols = context.trackedSymbols; - else - Debug.assert(context.trackedSymbols === oldContext.trackedSymbols); - } - context = oldContext; + scopeCleanup(); } } function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias, escapedSymbolName = symbol.escapedName) { @@ -57072,8 +57132,7 @@ function createTypeChecker(host) { if (symbol.declarations) { for (const node of symbol.declarations) { const resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); - if (!resolvedModule) - continue; + if (!resolvedModule) continue; addResult(factory.createExportDeclaration( /*modifiers*/ void 0, @@ -57113,8 +57172,7 @@ function createTypeChecker(host) { } } function includePrivateSymbol(symbol) { - if (some(symbol.declarations, isPartOfParameterDeclaration)) - return; + if (some(symbol.declarations, isPartOfParameterDeclaration)) return; Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]); getUnusedName(unescapeLeadingUnderscores(symbol.escapedName), symbol); const isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !some(symbol.declarations, (d) => !!findAncestor(d, isExportDeclaration) || isNamespaceExport(d) || isImportEqualsDeclaration(d) && !isExternalModuleReference(d.moduleReference)); @@ -57392,7 +57450,7 @@ function createTypeChecker(host) { } return cleanup(factory.createExpressionWithTypeArguments( expr, - map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode(a)) || typeToTypeNodeHelper(getTypeFromTypeNode(a), context)) + map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode2(context, a)) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context)) )); function cleanup(result2) { context.enclosingDeclaration = oldEnclosing; @@ -57505,8 +57563,7 @@ function createTypeChecker(host) { function serializeAsAlias(symbol, localName, modifierFlags) { var _a2, _b, _c, _d, _e, _f; const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); const target = getMergedSymbol(getTargetOfAliasDeclaration( node, /*dontRecursivelyResolve*/ @@ -58243,10 +58300,8 @@ function createTypeChecker(host) { result.push(t); } } - if (flags & 65536 /* Null */) - result.push(nullType); - if (flags & 32768 /* Undefined */) - result.push(undefinedType); + if (flags & 65536 /* Null */) result.push(nullType); + if (flags & 32768 /* Undefined */) result.push(undefinedType); return result || types; } function visibilityToString(flags) { @@ -58501,8 +58556,6 @@ function createTypeChecker(host) { switch (propertyName) { case 0 /* Type */: return !!getSymbolLinks(target).type; - case 5 /* EnumTagType */: - return !!getNodeLinks(target).resolvedEnumType; case 2 /* DeclaredType */: return !!getSymbolLinks(target).declaredType; case 1 /* ResolvedBaseConstructorType */: @@ -58511,13 +58564,13 @@ function createTypeChecker(host) { return !!target.resolvedReturnType; case 4 /* ImmediateBaseConstraint */: return !!target.immediateBaseConstraint; - case 6 /* ResolvedTypeArguments */: + case 5 /* ResolvedTypeArguments */: return !!target.resolvedTypeArguments; - case 7 /* ResolvedBaseTypes */: + case 6 /* ResolvedBaseTypes */: return !!target.baseTypesResolved; - case 8 /* WriteType */: + case 7 /* WriteType */: return !!getSymbolLinks(target).writeType; - case 9 /* ParameterInitializerContainsUndefined */: + case 8 /* ParameterInitializerContainsUndefined */: return getNodeLinks(target).parameterInitializerContainsUndefined !== void 0; } return Debug.assertNever(propertyName); @@ -58829,8 +58882,7 @@ function createTypeChecker(host) { } } const parameterTypeOfTypeTag = getParameterTypeOfTypeTag(func, declaration); - if (parameterTypeOfTypeTag) - return parameterTypeOfTypeTag; + if (parameterTypeOfTypeTag) return parameterTypeOfTypeTag; const type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration); if (type) { return addOptionality( @@ -59397,12 +59449,9 @@ function createTypeChecker(host) { result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : []; result.parent = symbol; result.links.target = fileSymbol; - if (fileSymbol.valueDeclaration) - result.valueDeclaration = fileSymbol.valueDeclaration; - if (fileSymbol.members) - result.members = new Map(fileSymbol.members); - if (fileSymbol.exports) - result.exports = new Map(fileSymbol.exports); + if (fileSymbol.valueDeclaration) result.valueDeclaration = fileSymbol.valueDeclaration; + if (fileSymbol.members) result.members = new Map(fileSymbol.members); + if (fileSymbol.exports) result.exports = new Map(fileSymbol.exports); const members = createSymbolTable(); members.set("exports", result); return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray); @@ -59533,14 +59582,14 @@ function createTypeChecker(host) { } type = anyType; } - links.type = type; + links.type ?? (links.type = type); } return links.type; } function getWriteTypeOfAccessors(symbol) { const links = getSymbolLinks(symbol); if (!links.writeType) { - if (!pushTypeResolution(symbol, 8 /* WriteType */)) { + if (!pushTypeResolution(symbol, 7 /* WriteType */)) { return errorType; } const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */) ?? tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); @@ -59551,7 +59600,7 @@ function createTypeChecker(host) { } writeType = anyType; } - links.writeType = writeType || getTypeOfAccessors(symbol); + links.writeType ?? (links.writeType = writeType || getTypeOfAccessors(symbol)); } return links.writeType; } @@ -59628,10 +59677,10 @@ function createTypeChecker(host) { true ); const declaredType = firstDefined(exportSymbol == null ? void 0 : exportSymbol.declarations, (d) => isExportAssignment(d) ? tryGetTypeFromEffectiveTypeNode(d) : void 0); - links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType; + links.type ?? (links.type = (exportSymbol == null ? void 0 : exportSymbol.declarations) && isDuplicatedCommonJSExport(exportSymbol.declarations) && symbol.declarations.length ? getFlowTypeFromCommonJSExport(exportSymbol) : isDuplicatedCommonJSExport(symbol.declarations) ? autoType : declaredType ? declaredType : getSymbolFlags(targetSymbol) & 111551 /* Value */ ? getTypeOfSymbol(targetSymbol) : errorType); if (!popTypeResolution()) { reportCircularityError(exportSymbol ?? symbol); - return links.type = errorType; + return links.type ?? (links.type = errorType); } } return links.type; @@ -59897,7 +59946,7 @@ function createTypeChecker(host) { } if (!popTypeResolution()) { error2(type.symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol)); - return type.resolvedBaseConstructorType = errorType; + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); } if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) { const err = error2(baseTypeNode.expression, Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType)); @@ -59914,9 +59963,9 @@ function createTypeChecker(host) { addRelatedInfo(err, createDiagnosticForNode(baseConstructorType.symbol.declarations[0], Diagnostics.Did_you_mean_for_0_to_be_constrained_to_type_new_args_Colon_any_1, symbolToString(baseConstructorType.symbol), typeToString(ctorReturn))); } } - return type.resolvedBaseConstructorType = errorType; + return type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = errorType); } - type.resolvedBaseConstructorType = baseConstructorType; + type.resolvedBaseConstructorType ?? (type.resolvedBaseConstructorType = baseConstructorType); } return type.resolvedBaseConstructorType; } @@ -59925,8 +59974,7 @@ function createTypeChecker(host) { if (type.symbol.declarations) { for (const declaration of type.symbol.declarations) { const implementsTypeNodes = getEffectiveImplementsTypeNodes(declaration); - if (!implementsTypeNodes) - continue; + if (!implementsTypeNodes) continue; for (const node of implementsTypeNodes) { const implementsType = getTypeFromTypeNode(node); if (!isErrorType(implementsType)) { @@ -59951,7 +59999,7 @@ function createTypeChecker(host) { } function getBaseTypes(type) { if (!type.baseTypesResolved) { - if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) { + if (pushTypeResolution(type, 6 /* ResolvedBaseTypes */)) { if (type.objectFlags & 8 /* Tuple */) { type.resolvedBaseTypes = [getTupleBaseType(type)]; } else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) { @@ -60157,7 +60205,7 @@ function createTypeChecker(host) { error2(isNamedDeclaration(declaration) ? declaration.name || declaration : declaration, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } } - links.declaredType = type; + links.declaredType ?? (links.declaredType = type); } return links.declaredType; } @@ -60387,8 +60435,7 @@ function createTypeChecker(host) { const memberName = getPropertyNameFromType(type); const symbolFlags = decl.symbol.flags; let lateSymbol = lateSymbols.get(memberName); - if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); + if (!lateSymbol) lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */)); const earlySymbol = earlySymbols && earlySymbols.get(memberName); if (!(parent2.flags & 32 /* Class */) && lateSymbol.flags & getExcludedSymbolFlags(symbolFlags)) { const declarations = earlySymbol ? concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; @@ -60449,16 +60496,12 @@ function createTypeChecker(host) { resolved = original; continue; } - if (!original) - continue; + if (!original) continue; original.forEach((s, name) => { const existing = resolved.get(name); - if (!existing) - resolved.set(name, s); - else if (existing === s) - return; - else - resolved.set(name, mergeSymbol(existing, s)); + if (!existing) resolved.set(name, s); + else if (existing === s) return; + else resolved.set(name, mergeSymbol(existing, s)); }); } } @@ -60753,8 +60796,7 @@ function createTypeChecker(host) { let result; let indexWithLengthOverOne; for (let i = 0; i < signatureLists.length; i++) { - if (signatureLists[i].length === 0) - return emptyArray; + if (signatureLists[i].length === 0) return emptyArray; if (signatureLists[i].length > 1) { indexWithLengthOverOne = indexWithLengthOverOne === void 0 ? i : -1; } @@ -60815,10 +60857,8 @@ function createTypeChecker(host) { for (let i = 0; i < sourceParams.length; i++) { const source = sourceParams[i]; const target = targetParams[i]; - if (source === target) - continue; - if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) - return false; + if (source === target) continue; + if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper))) return false; } return true; } @@ -61275,6 +61315,7 @@ function createTypeChecker(host) { } } function getTypeOfMappedSymbol(symbol) { + var _a; if (!symbol.links.type) { const mappedType = symbol.links.mappedType; if (!pushTypeResolution(symbol, 0 /* Type */)) { @@ -61293,7 +61334,7 @@ function createTypeChecker(host) { error2(currentNode, Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType)); type = errorType; } - symbol.links.type = type; + (_a = symbol.links).type ?? (_a.type = type); } return symbol.links.type; } @@ -61474,8 +61515,7 @@ function createTypeChecker(host) { for (const { escapedName } of getAugmentedPropertiesOfType(memberType)) { if (!props.has(escapedName)) { const prop = createUnionOrIntersectionProperty(unionType, escapedName); - if (prop) - props.set(escapedName, prop); + if (prop) props.set(escapedName, prop); } } } @@ -61592,7 +61632,7 @@ function createTypeChecker(host) { } } return getNormalizedType( - getIntersectionType(constraints), + getIntersectionType(constraints, 2 /* NoConstraintReduction */), /*writing*/ false ); @@ -61646,7 +61686,7 @@ function createTypeChecker(host) { } result = circularConstraintType; } - t.immediateBaseConstraint = result || noConstraintType; + t.immediateBaseConstraint ?? (t.immediateBaseConstraint = result || noConstraintType); } return t.immediateBaseConstraint; } @@ -61718,7 +61758,16 @@ function createTypeChecker(host) { } } function getApparentTypeOfIntersectionType(type, thisArgument) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( + if (type === thisArgument) { + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument( + type, + thisArgument, + /*needApparentType*/ + true + )); + } + const key = `I${getTypeId(type)},${getTypeId(thisArgument)}`; + return getCachedType(key) ?? setCachedType(key, getTypeWithThisArgument( type, thisArgument, /*needApparentType*/ @@ -62036,8 +62085,7 @@ function createTypeChecker(host) { if (symbol && symbolIsValue(symbol, includeTypeOnlyMembers)) { return symbol; } - if (skipObjectFunctionPropertyAugment) - return void 0; + if (skipObjectFunctionPropertyAugment) return void 0; const functionType = resolved === anyFunctionType ? globalFunctionType : resolved.callSignatures.length ? globalCallableFunctionType : resolved.constructSignatures.length ? globalNewableFunctionType : void 0; if (functionType) { const symbol2 = getPropertyOfObjectType(functionType, name); @@ -62352,15 +62400,13 @@ function createTypeChecker(host) { return true; } function getSignatureOfTypeTag(node) { - if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) - return void 0; + if (!(isInJSFile(node) && isFunctionLikeDeclaration(node))) return void 0; const typeTag = getJSDocTypeTag(node); return (typeTag == null ? void 0 : typeTag.typeExpression) && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); } function getParameterTypeOfTypeTag(func, parameter) { const signature = getSignatureOfTypeTag(func); - if (!signature) - return void 0; + if (!signature) return void 0; const pos = func.parameters.indexOf(parameter); return parameter.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos); } @@ -62379,8 +62425,7 @@ function createTypeChecker(host) { } return links.containsArgumentsReference; function traverse(node) { - if (!node) - return false; + if (!node) return false; switch (node.kind) { case 80 /* Identifier */: return node.escapedText === argumentsSymbol.escapedName && getReferencedValueSymbol(node) === argumentsSymbol; @@ -62400,13 +62445,11 @@ function createTypeChecker(host) { } } function getSignaturesOfSymbol(symbol) { - if (!symbol || !symbol.declarations) - return emptyArray; + if (!symbol || !symbol.declarations) return emptyArray; const result = []; for (let i = 0; i < symbol.declarations.length; i++) { const decl = symbol.declarations[i]; - if (!isFunctionLike(decl)) - continue; + if (!isFunctionLike(decl)) continue; if (i > 0 && decl.body) { const previous = symbol.declarations[i - 1]; if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) { @@ -62520,7 +62563,7 @@ function createTypeChecker(host) { } type = anyType; } - signature.resolvedReturnType = type; + signature.resolvedReturnType ?? (signature.resolvedReturnType = type); } return signature.resolvedReturnType; } @@ -62860,15 +62903,15 @@ function createTypeChecker(host) { function getTypeArguments(type) { var _a, _b; if (!type.resolvedTypeArguments) { - if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) { + if (!pushTypeResolution(type, 5 /* ResolvedTypeArguments */)) { return ((_a = type.target.localTypeParameters) == null ? void 0 : _a.map(() => errorType)) || emptyArray; } const node = type.node; const typeArguments = !node ? emptyArray : node.kind === 183 /* TypeReference */ ? concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments2(node, type.target.localTypeParameters)) : node.kind === 188 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : map(node.elements, getTypeFromTypeNode); if (popTypeResolution()) { - type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments; + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments); } else { - type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray; + type.resolvedTypeArguments ?? (type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) == null ? void 0 : _b.map(() => errorType)) || emptyArray); error2( type.node || currentNode, type.target.symbol ? Diagnostics.Type_arguments_for_0_circularly_reference_themselves : Diagnostics.Tuple_type_arguments_circularly_reference_themselves, @@ -63797,8 +63840,7 @@ function createTypeChecker(host) { lengthSymbol.links.type = numberType; } else { const literalTypes = []; - for (let i = minLength; i <= arity; i++) - literalTypes.push(getNumberLiteralType(i)); + for (let i = minLength; i <= arity; i++) literalTypes.push(getNumberLiteralType(i)); lengthSymbol.links.type = getUnionType(literalTypes); } properties.push(lengthSymbol); @@ -63875,8 +63917,7 @@ function createTypeChecker(host) { } } for (let i = 0; i < lastRequiredIndex; i++) { - if (expandedFlags[i] & 2 /* Optional */) - expandedFlags[i] = 1 /* Required */; + if (expandedFlags[i] & 2 /* Optional */) expandedFlags[i] = 1 /* Required */; } if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) { expandedTypes[firstRestIndex] = getUnionType(sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), (t, i) => expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t)); @@ -63959,15 +64000,12 @@ function createTypeChecker(host) { const flags = type.flags; if (!(flags & 131072 /* Never */)) { includes |= flags & 473694207 /* IncludesMask */; - if (flags & 465829888 /* Instantiable */) - includes |= 33554432 /* IncludesInstantiable */; - if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) - includes |= 536870912 /* IncludesConstrainedTypeVariable */; - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (flags & 465829888 /* Instantiable */) includes |= 33554432 /* IncludesInstantiable */; + if (flags & 2097152 /* Intersection */ && getObjectFlags(type) & 67108864 /* IsConstrainedTypeVariable */) includes |= 536870912 /* IncludesConstrainedTypeVariable */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; if (!strictNullChecks && flags & 98304 /* Nullable */) { - if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) - includes |= 4194304 /* IncludesNonWideningType */; + if (!(getObjectFlags(type) & 65536 /* ContainsWideningType */)) includes |= 4194304 /* IncludesNonWideningType */; } else { const len = typeSet.length; const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); @@ -64157,7 +64195,7 @@ function createTypeChecker(host) { const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== 0 /* None */) { if (includes & 3 /* AnyOrUnknown */) { - return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType; + return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType : unknownType; } if (includes & 32768 /* Undefined */) { if (typeSet.length >= 2 && typeSet[0] === undefinedType && typeSet[1] === missingType) { @@ -64282,8 +64320,8 @@ function createTypeChecker(host) { } } else { if (flags & 3 /* AnyOrUnknown */) { - if (type === wildcardType) - includes |= 8388608 /* IncludesWildcard */; + if (type === wildcardType) includes |= 8388608 /* IncludesWildcard */; + if (isErrorType(type)) includes |= 1073741824 /* IncludesError */; } else if (strictNullChecks || !(flags & 98304 /* Nullable */)) { if (type === missingType) { includes |= 262144 /* IncludesMissingType */; @@ -64334,8 +64372,7 @@ function createTypeChecker(host) { while (i > 0) { i--; const t = types[i]; - if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */))) - continue; + if (!(t.flags & (134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */))) continue; for (const t2 of literals) { if (isTypeSubtypeOf(t2, t)) { orderedRemoveItemAt(types, i); @@ -64397,7 +64434,7 @@ function createTypeChecker(host) { result.aliasTypeArguments = aliasTypeArguments; return result; } - function getIntersectionType(types, aliasSymbol, aliasTypeArguments, noSupertypeReduction) { + function getIntersectionType(types, flags = 0 /* None */, aliasSymbol, aliasTypeArguments) { const typeMembershipMap = /* @__PURE__ */ new Map(); const includes = addTypesToIntersection(typeMembershipMap, 0, types); const typeSet = arrayFrom(typeMembershipMap.values()); @@ -64412,14 +64449,13 @@ function createTypeChecker(host) { return neverType; } if (includes & 1 /* Any */) { - return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType; + return includes & 8388608 /* IncludesWildcard */ ? wildcardType : includes & 1073741824 /* IncludesError */ ? errorType : anyType; } if (!strictNullChecks && includes & 98304 /* Nullable */) { return includes & 16777216 /* IncludesEmptyObject */ ? neverType : includes & 32768 /* Undefined */ ? undefinedType : nullType; } if (includes & 4 /* String */ && includes & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ || includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ || includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */ || includes & 16384 /* Void */ && includes & 32768 /* Undefined */ || includes & 16777216 /* IncludesEmptyObject */ && includes & 470302716 /* DefinitelyNonNullable */) { - if (!noSupertypeReduction) - removeRedundantSupertypes(typeSet, includes); + if (!(flags & 1 /* NoSupertypeReduction */)) removeRedundantSupertypes(typeSet, includes); } if (includes & 262144 /* IncludesMissingType */) { typeSet[typeSet.indexOf(undefinedType)] = missingType; @@ -64430,7 +64466,7 @@ function createTypeChecker(host) { if (typeSet.length === 1) { return typeSet[0]; } - if (typeSet.length === 2) { + if (typeSet.length === 2 && !(flags & 2 /* NoConstraintReduction */)) { const typeVarIndex = typeSet[0].flags & 8650752 /* TypeVariable */ ? 0 : 1; const typeVariable = typeSet[typeVarIndex]; const primitiveType = typeSet[1 - typeVarIndex]; @@ -64449,27 +64485,27 @@ function createTypeChecker(host) { } } } - const id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments); + const id = getTypeListId(typeSet) + (flags & 2 /* NoConstraintReduction */ ? "*" : getAliasId(aliasSymbol, aliasTypeArguments)); let result = intersectionTypes.get(id); if (!result) { if (includes & 1048576 /* Union */) { if (intersectUnionsOfPrimitiveTypes(typeSet)) { - result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments); + result = getIntersectionType(typeSet, flags, aliasSymbol, aliasTypeArguments); } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && t.types[0].flags & 32768 /* Undefined */))) { const containedUndefinedType = some(typeSet, containsMissingType) ? missingType : undefinedType; removeFromEach(typeSet, 32768 /* Undefined */); - result = getUnionType([getIntersectionType(typeSet), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + result = getUnionType([getIntersectionType(typeSet, flags), containedUndefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); } else if (every(typeSet, (t) => !!(t.flags & 1048576 /* Union */ && (t.types[0].flags & 65536 /* Null */ || t.types[1].flags & 65536 /* Null */)))) { removeFromEach(typeSet, 65536 /* Null */); - result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); + result = getUnionType([getIntersectionType(typeSet, flags), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments); } else if (typeSet.length >= 4) { const middle = Math.floor(typeSet.length / 2); - result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle)), getIntersectionType(typeSet.slice(middle))], aliasSymbol, aliasTypeArguments); + result = getIntersectionType([getIntersectionType(typeSet.slice(0, middle), flags), getIntersectionType(typeSet.slice(middle), flags)], flags, aliasSymbol, aliasTypeArguments); } else { if (!checkCrossProductUnion(typeSet)) { return errorType; } - const constituents = getCrossProductIntersections(typeSet); + const constituents = getCrossProductIntersections(typeSet, flags); const origin = some(constituents, (t) => !!(t.flags & 2097152 /* Intersection */)) && getConstituentCountOfTypes(constituents) > getConstituentCountOfTypes(typeSet) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : void 0; result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin); } @@ -64493,7 +64529,7 @@ function createTypeChecker(host) { } return true; } - function getCrossProductIntersections(types) { + function getCrossProductIntersections(types, flags) { const count = getCrossProductUnionSize(types); const intersections = []; for (let i = 0; i < count; i++) { @@ -64507,9 +64543,8 @@ function createTypeChecker(host) { n = Math.floor(n / length2); } } - const t = getIntersectionType(constituents); - if (!(t.flags & 131072 /* Never */)) - intersections.push(t); + const t = getIntersectionType(constituents, flags); + if (!(t.flags & 131072 /* Never */)) intersections.push(t); } return intersections; } @@ -64527,7 +64562,7 @@ function createTypeChecker(host) { const emptyIndex = types.length === 2 ? types.indexOf(emptyTypeLiteralType) : -1; const t = emptyIndex >= 0 ? types[1 - emptyIndex] : unknownType; const noSupertypeReduction = !!(t.flags & (4 /* String */ | 8 /* Number */ | 64 /* BigInt */) || t.flags & 134217728 /* TemplateLiteral */ && isPatternLiteralType(t)); - links.resolvedType = getIntersectionType(types, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol), noSupertypeReduction); + links.resolvedType = getIntersectionType(types, noSupertypeReduction ? 1 /* NoSupertypeReduction */ : 0, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol)); } return links.resolvedType; } @@ -64675,7 +64710,6 @@ function createTypeChecker(host) { return links.resolvedType; } function getTemplateLiteralType(texts, types) { - var _a, _b; const unionIndex = findIndex(types, (t) => !!(t.flags & (131072 /* Never */ | 1048576 /* Union */))); if (unionIndex >= 0) { return checkCrossProductUnion(types) ? mapType(types[unionIndex], (t) => getTemplateLiteralType(texts, replaceElement(types, unionIndex, t))) : errorType; @@ -64683,9 +64717,6 @@ function createTypeChecker(host) { if (contains(types, wildcardType)) { return wildcardType; } - if (texts.length === 2 && texts[0] === "" && texts[1] === "" && !(types[0].flags & 2944 /* Literal */) && !((_b = (_a = types[0].symbol) == null ? void 0 : _a.declarations) == null ? void 0 : _b.some((d) => d.parent.kind === 195 /* InferType */)) && isTypeAssignableTo(types[0], stringType)) { - return types[0]; - } const newTypes = []; const newTexts = []; let text = texts[0]; @@ -64718,8 +64749,7 @@ function createTypeChecker(host) { text += texts2[i + 1]; } else if (t.flags & 134217728 /* TemplateLiteral */) { text += t.texts[0]; - if (!addSpans(t.texts, t.types)) - return false; + if (!addSpans(t.texts, t.types)) return false; text += texts2[i + 1]; } else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) { newTypes.push(t); @@ -65187,8 +65217,7 @@ function createTypeChecker(host) { if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) { indexType = stringType; } - if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) - accessFlags |= 1 /* IncludeUndefined */; + if (compilerOptions.noUncheckedIndexedAccess && accessFlags & 32 /* ExpressionPosition */) accessFlags |= 1 /* IncludeUndefined */; if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 199 /* IndexedAccessType */ ? isGenericTupleType(objectType) && !indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target)) : isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, getTotalFixedElementCount(objectType.target))) || isGenericReducibleType(objectType))) { if (objectType.flags & 3 /* AnyOrUnknown */) { return objectType; @@ -65218,7 +65247,7 @@ function createTypeChecker(host) { if (wasMissingProp) { return void 0; } - return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments); + return accessFlags & 4 /* Writing */ ? getIntersectionType(propTypes, 0 /* None */, aliasSymbol, aliasTypeArguments) : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments); } return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, accessNode, accessFlags | 8 /* CacheSymbol */ | 64 /* ReportDeprecated */); } @@ -66342,7 +66371,7 @@ function createTypeChecker(host) { } const newAliasSymbol = aliasSymbol || type.aliasSymbol; const newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper); - return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); + return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ? getIntersectionType(newTypes, 0 /* None */, newAliasSymbol, newAliasTypeArguments) : getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments); } if (flags & 4194304 /* Index */) { return getIndexType(instantiateType(type.type, mapper)); @@ -66540,8 +66569,7 @@ function createTypeChecker(host) { ); } function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) { - if (isTypeRelatedTo(source, target, relation)) - return true; + if (isTypeRelatedTo(source, target, relation)) return true; if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer); } @@ -66551,8 +66579,7 @@ function createTypeChecker(host) { return !!(type.flags & 16777216 /* Conditional */ || type.flags & 2097152 /* Intersection */ && some(type.types, isOrHasGenericConditional)); } function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) { - if (!node || isOrHasGenericConditional(target)) - return false; + if (!node || isOrHasGenericConditional(target)) return false; if (!checkTypeRelatedTo( source, target, @@ -66724,11 +66751,9 @@ function createTypeChecker(host) { for (const value of iterator) { const { errorNode: prop, innerExpression: next, nameType, errorMessage } = value; let targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType); - if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) - continue; + if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; + if (!sourcePropType) continue; const propName = getPropertyNameFromIndex( nameType, /*accessNode*/ @@ -66819,11 +66844,9 @@ function createTypeChecker(host) { if (targetIndexedPropType && !(targetIndexedPropType.flags & 8388608 /* IndexedAccess */)) { targetPropType = iterationType ? getUnionType([iterationType, targetIndexedPropType]) : targetIndexedPropType; } - if (!targetPropType) - continue; + if (!targetPropType) continue; let sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType); - if (!sourcePropType) - continue; + if (!sourcePropType) continue; const propName = getPropertyNameFromIndex( nameType, /*accessNode*/ @@ -66870,17 +66893,14 @@ function createTypeChecker(host) { return reportedError; } function* generateJsxAttributes(node) { - if (!length(node.properties)) - return; + if (!length(node.properties)) return; for (const prop of node.properties) { - if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) - continue; + if (isJsxSpreadAttribute(prop) || isHyphenatedJsxName(getTextOfJsxAttributeName(prop.name))) continue; yield { errorNode: prop.name, innerExpression: prop.initializer, nameType: getStringLiteralType(getTextOfJsxAttributeName(prop.name)) }; } } function* generateJsxChildren(node, getInvalidTextDiagnostic) { - if (!length(node.children)) - return; + if (!length(node.children)) return; let memberOffset = 0; for (let i = 0; i < node.children.length; i++) { const child = node.children[i]; @@ -67000,22 +67020,18 @@ function createTypeChecker(host) { } function* generateLimitedTupleElements(node, target) { const len = length(node.elements); - if (!len) - return; + if (!len) return; for (let i = 0; i < len; i++) { - if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) - continue; + if (isTupleLikeType(target) && !getPropertyOfType(target, "" + i)) continue; const elem = node.elements[i]; - if (isOmittedExpression(elem)) - continue; + if (isOmittedExpression(elem)) continue; const nameType = getNumberLiteralType(i); const checkNode = getEffectiveCheckNode(elem); yield { errorNode: checkNode, innerExpression: checkNode, nameType }; } } function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) - return false; + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; if (isTupleLikeType(source)) { return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer); } @@ -67038,11 +67054,9 @@ function createTypeChecker(host) { return false; } function* generateObjectLiteralElements(node) { - if (!length(node.properties)) - return; + if (!length(node.properties)) return; for (const prop of node.properties) { - if (isSpreadAssignment(prop)) - continue; + if (isSpreadAssignment(prop)) continue; const type = getLiteralTypeFromProperty(getSymbolOfDeclaration(prop), 8576 /* StringOrNumberLiteralOrUnique */); if (!type || type.flags & 131072 /* Never */) { continue; @@ -67063,8 +67077,7 @@ function createTypeChecker(host) { } } function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) { - if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) - return false; + if (target.flags & (402784252 /* Primitive */ | 131072 /* Never */)) return false; return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer); } function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) { @@ -67155,7 +67168,7 @@ function createTypeChecker(host) { for (let i = 0; i < paramCount; i++) { const sourceType = i === restIndex ? getRestOrAnyTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i); const targetType = i === restIndex ? getRestOrAnyTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i); - if (sourceType && targetType) { + if (sourceType && targetType && (sourceType !== targetType || checkMode & 8 /* StrictArity */)) { const sourceSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(source, i) ? void 0 : getSingleCallSignature(getNonNullableType(sourceType)); const targetSig = checkMode & 3 /* Callback */ || isInstantiatedGenericParameter(target, i) ? void 0 : getSingleCallSignature(getNonNullableType(targetType)); const callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) && getTypeFacts(sourceType, 50331648 /* IsUndefinedOrNull */) === getTypeFacts(targetType, 50331648 /* IsUndefinedOrNull */); @@ -67345,49 +67358,29 @@ function createTypeChecker(host) { function isSimpleTypeRelatedTo(source, target, relation, errorReporter) { const s = source.flags; const t = target.flags; - if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) - return true; - if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) - return true; - if (t & 131072 /* Never */) - return false; - if (s & 402653316 /* StringLike */ && t & 4 /* String */) - return true; - if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) - return true; - if (s & 296 /* NumberLike */ && t & 8 /* Number */) - return true; - if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) - return true; - if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) - return true; - if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) - return true; - if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) - return true; - if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; + if (t & 1 /* Any */ || s & 131072 /* Never */ || source === wildcardType) return true; + if (t & 2 /* Unknown */ && !(relation === strictSubtypeRelation && s & 1 /* Any */)) return true; + if (t & 131072 /* Never */) return false; + if (s & 402653316 /* StringLike */ && t & 4 /* String */) return true; + if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ && t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 296 /* NumberLike */ && t & 8 /* Number */) return true; + if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ && t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) && source.value === target.value) return true; + if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */) return true; + if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */) return true; + if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */) return true; + if (s & 32 /* Enum */ && t & 32 /* Enum */ && source.symbol.escapedName === target.symbol.escapedName && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) { - if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; - if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) - return true; + if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; + if (s & 2944 /* Literal */ && t & 2944 /* Literal */ && source.value === target.value && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter)) return true; } - if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) - return true; - if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) - return true; - if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) - return true; + if (s & 32768 /* Undefined */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & (32768 /* Undefined */ | 16384 /* Void */))) return true; + if (s & 65536 /* Null */ && (!strictNullChecks && !(t & 3145728 /* UnionOrIntersection */) || t & 65536 /* Null */)) return true; + if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */ && !(relation === strictSubtypeRelation && isEmptyAnonymousObjectType(source) && !(getObjectFlags(source) & 8192 /* FreshLiteral */))) return true; if (relation === assignableRelation || relation === comparableRelation) { - if (s & 1 /* Any */) - return true; - if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) - return true; - if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */ && source.value === target.value)) - return true; - if (isUnknownLikeUnionType(target)) - return true; + if (s & 1 /* Any */) return true; + if (s & 8 /* Number */ && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */)) return true; + if (s & 256 /* NumberLiteral */ && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */ && source.value === target.value)) return true; + if (isUnknownLikeUnionType(target)) return true; } return false; } @@ -67406,10 +67399,8 @@ function createTypeChecker(host) { return true; } } else if (!((source.flags | target.flags) & (3145728 /* UnionOrIntersection */ | 8388608 /* IndexedAccess */ | 16777216 /* Conditional */ | 33554432 /* Substitution */))) { - if (source.flags !== target.flags) - return false; - if (source.flags & 67358815 /* Singleton */) - return true; + if (source.flags !== target.flags) return false; + if (source.flags & 67358815 /* Singleton */) return true; } if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) { const related = relation.get(getRelationKey( @@ -67441,8 +67432,7 @@ function createTypeChecker(host) { function getNormalizedType(type, writing) { while (true) { const t = isFreshLiteralType(type) ? type.regularType : isGenericTupleType(type) ? getNormalizedTupleType(type, writing) : getObjectFlags(type) & 4 /* Reference */ ? type.node ? createTypeReference(type.target, getTypeArguments(type)) : getSingleBaseForNonAugmentingSubtype(type) || type : type.flags & 3145728 /* UnionOrIntersection */ ? getNormalizedUnionOrIntersectionType(type, writing) : type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : getSubstitutionIntersection(type) : type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) : type; - if (t === type) - return t; + if (t === type) return t; type = t; } } @@ -67465,8 +67455,7 @@ function createTypeChecker(host) { for (const t of type.types) { hasInstantiable || (hasInstantiable = !!(t.flags & 465829888 /* Instantiable */)); hasNullableOrEmpty || (hasNullableOrEmpty = !!(t.flags & 98304 /* Nullable */) || isEmptyAnonymousObjectType(t)); - if (hasInstantiable && hasNullableOrEmpty) - return true; + if (hasInstantiable && hasNullableOrEmpty) return true; } return false; } @@ -67677,10 +67666,8 @@ function createTypeChecker(host) { } function reportError(message, ...args) { Debug.assert(!!errorNode); - if (incompatibleStack) - reportIncompatibleStack(); - if (message.elidedInCompatabilityPyramid) - return; + if (incompatibleStack) reportIncompatibleStack(); + if (message.elidedInCompatabilityPyramid) return; if (skipParentCounter === 0) { errorInfo = chainDiagnosticMessages(errorInfo, message, ...args); } else { @@ -67700,8 +67687,7 @@ function createTypeChecker(host) { } } function reportRelationError(message, source2, target2) { - if (incompatibleStack) - reportIncompatibleStack(); + if (incompatibleStack) reportIncompatibleStack(); const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2); let generalizedSource = source2; let generalizedSourceType = sourceType; @@ -67784,8 +67770,7 @@ function createTypeChecker(host) { return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { - if (originalSource === originalTarget) - return -1 /* True */; + if (originalSource === originalTarget) return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -67805,13 +67790,10 @@ function createTypeChecker(host) { /*writing*/ true ); - if (source2 === target2) - return -1 /* True */; + if (source2 === target2) return -1 /* True */; if (relation === identityRelation) { - if (source2.flags !== target2.flags) - return 0 /* False */; - if (source2.flags & 67358815 /* Singleton */) - return -1 /* True */; + if (source2.flags !== target2.flags) return 0 /* False */; + if (source2.flags & 67358815 /* Singleton */) return -1 /* True */; traceUnionsOrIntersectionsTooLarge(source2, target2); return recursiveTypeRelatedTo( source2, @@ -67834,12 +67816,10 @@ function createTypeChecker(host) { /*writing*/ true ); - if (source2 === target2) - return -1 /* True */; + if (source2 === target2) return -1 /* True */; } } - if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) - return -1 /* True */; + if (relation === comparableRelation && !(target2.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target2, source2, relation) || isSimpleTypeRelatedTo(source2, target2, relation, reportErrors2 ? reportError : void 0)) return -1 /* True */; if (source2.flags & 469499904 /* StructuredOrInstantiable */ || target2.flags & 469499904 /* StructuredOrInstantiable */) { const isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType2(source2) && getObjectFlags(source2) & 8192 /* FreshLiteral */); if (isPerformingExcessPropertyChecks) { @@ -67927,6 +67907,16 @@ function createTypeChecker(host) { errorInfo = elaborateNeverIntersection(errorInfo, originalTarget); } if (!headMessage2 && maybeSuppress) { + const savedErrorState = captureErrorCalculationState(); + reportRelationError(headMessage2, source2, target2); + let canonical; + if (errorInfo && errorInfo !== savedErrorState.errorInfo) { + canonical = { code: errorInfo.code, messageText: errorInfo.messageText }; + } + resetErrorInfo(savedErrorState); + if (canonical && errorInfo) { + errorInfo.canonicalHead = canonical; + } lastSkippedInfo = [source2, target2]; return; } @@ -67999,8 +67989,7 @@ function createTypeChecker(host) { if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors2) { const errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget); - if (!errorNode) - return Debug.fail(); + if (!errorNode) return Debug.fail(); if (isJsxAttributes(errorNode) || isJsxOpeningLikeElement(errorNode) || isJsxOpeningLikeElement(errorNode.parent)) { if (prop.valueDeclaration && isJsxAttribute(prop.valueDeclaration) && getSourceFileOfNode(errorNode) === getSourceFileOfNode(prop.valueDeclaration.name)) { errorNode = prop.valueDeclaration.name; @@ -68419,14 +68408,12 @@ function createTypeChecker(host) { if (recursionFlags & 1 /* Source */) { sourceStack[sourceDepth] = source2; sourceDepth++; - if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) - expandingFlags |= 1 /* Source */; + if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source2, sourceStack, sourceDepth)) expandingFlags |= 1 /* Source */; } if (recursionFlags & 2 /* Target */) { targetStack[targetDepth] = target2; targetDepth++; - if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) - expandingFlags |= 2 /* Target */; + if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target2, targetStack, targetDepth)) expandingFlags |= 2 /* Target */; } let originalHandler; let propagatingVarianceFlags = 0; @@ -69080,8 +69067,7 @@ function createTypeChecker(host) { } return 0 /* False */; function countMessageChainBreadth(info) { - if (!info) - return 0; + if (!info) return 0; return reduceLeft(info, (value, chain) => value + 1 + countMessageChainBreadth(chain.next), 0); } function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState2) { @@ -69123,8 +69109,7 @@ function createTypeChecker(host) { var _a2; const sourceProperties = getPropertiesOfType(source2); const sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target2); - if (!sourcePropertiesFiltered) - return 0 /* False */; + if (!sourcePropertiesFiltered) return 0 /* False */; let numCombinations = 1; for (const sourceProperty of sourcePropertiesFiltered) { numCombinations *= countTypes(getNonMissingTypeOfSymbol(sourceProperty)); @@ -69150,10 +69135,8 @@ function createTypeChecker(host) { for (let i = 0; i < sourcePropertiesFiltered.length; i++) { const sourceProperty = sourcePropertiesFiltered[i]; const targetProperty = getPropertyOfType(type, sourceProperty.escapedName); - if (!targetProperty) - continue outer; - if (sourceProperty === targetProperty) - continue; + if (!targetProperty) continue outer; + if (sourceProperty === targetProperty) continue; const related = propertyRelatedTo( source2, target2, @@ -69227,8 +69210,7 @@ function createTypeChecker(host) { return result2; } function excludeProperties(properties, excludedProperties) { - if (!excludedProperties || properties.length === 0) - return properties; + if (!excludedProperties || properties.length === 0) return properties; let result2; for (let i = 0; i < properties.length; i++) { if (!excludedProperties.has(properties[i].escapedName)) { @@ -69845,8 +69827,7 @@ function createTypeChecker(host) { return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* StringMapping */); } function getExactOptionalUnassignableProperties(source, target) { - if (isTupleType(source) && isTupleType(target)) - return emptyArray; + if (isTupleType(source) && isTupleType(target)) return emptyArray; return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp))); } function isExactOptionalPropertyMismatch(source, target) { @@ -69915,6 +69896,7 @@ function createTypeChecker(host) { if (!links.variances) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) }); const oldVarianceComputation = inVarianceComputation; + const saveResolutionStart = resolutionStart; if (!inVarianceComputation) { inVarianceComputation = true; resolutionStart = resolutionTargets.length; @@ -69949,7 +69931,7 @@ function createTypeChecker(host) { } if (!oldVarianceComputation) { inVarianceComputation = false; - resolutionStart = 0; + resolutionStart = saveResolutionStart; } links.variances = variances; (_b = tracing) == null ? void 0 : _b.pop({ variances: variances.map(Debug.formatVariance) }); @@ -70789,12 +70771,17 @@ function createTypeChecker(host) { } } function applyToReturnTypes(source, target, callback) { - const sourceTypePredicate = getTypePredicateOfSignature(source); const targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) { - callback(sourceTypePredicate.type, targetTypePredicate.type); - } else { - callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + if (targetTypePredicate) { + const sourceTypePredicate = getTypePredicateOfSignature(source); + if (sourceTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + return; + } + } + const targetReturnType = getReturnTypeOfSignature(target); + if (couldContainTypeVariables(targetReturnType)) { + callback(getReturnTypeOfSignature(source), targetReturnType); } } function createInferenceContext(typeParameters, signature, flags, compareTypes) { @@ -71008,10 +70995,8 @@ function createTypeChecker(host) { reverseMappedSourceStack.push(source); reverseMappedTargetStack.push(target); const saveExpandingFlags = reverseExpandingFlags; - if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) - reverseExpandingFlags |= 1 /* Source */; - if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) - reverseExpandingFlags |= 2 /* Target */; + if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) reverseExpandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) reverseExpandingFlags |= 2 /* Target */; let type; if (reverseExpandingFlags !== 3 /* Both */) { type = inferReverseMappedTypeWorker(source, target, constraint); @@ -71086,8 +71071,7 @@ function createTypeChecker(host) { return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen); } function isValidNumberString(s, roundTripOnly) { - if (s === "") - return false; + if (s === "") return false; const n = +s; return isFinite(n) && (!roundTripOnly || "" + n === s); } @@ -71157,8 +71141,7 @@ function createTypeChecker(host) { const lastTargetIndex = targetTexts.length - 1; const targetStartText = targetTexts[0]; const targetEndText = targetTexts[lastTargetIndex]; - if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) - return void 0; + if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return void 0; const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length); const matches = []; let seg = 0; @@ -71170,11 +71153,9 @@ function createTypeChecker(host) { let p = pos; while (true) { p = getSourceText(s).indexOf(delim, p); - if (p >= 0) - break; + if (p >= 0) break; s++; - if (s === sourceTexts.length) - return void 0; + if (s === sourceTexts.length) return void 0; p = 0; } addMatch(s, p); @@ -71417,10 +71398,8 @@ function createTypeChecker(host) { const saveExpandingFlags = expandingFlags; (sourceStack ?? (sourceStack = [])).push(source); (targetStack ?? (targetStack = [])).push(target); - if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) - expandingFlags |= 1 /* Source */; - if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) - expandingFlags |= 2 /* Target */; + if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */; + if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */; if (expandingFlags !== 3 /* Both */) { action(source, target); } else { @@ -71508,8 +71487,7 @@ function createTypeChecker(host) { const saveInferencePriority = inferencePriority; inferencePriority = 2048 /* MaxValue */; inferFromTypes(sources[i], t); - if (inferencePriority === priority) - matched[i] = true; + if (inferencePriority === priority) matched[i] = true; inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */; inferencePriority = Math.min(inferencePriority, saveInferencePriority); } @@ -71642,8 +71620,7 @@ function createTypeChecker(host) { inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target)); const sourceNameType = getNameTypeFromMappedType(source); const targetNameType = getNameTypeFromMappedType(target); - if (sourceNameType && targetNameType) - inferFromTypes(sourceNameType, targetNameType); + if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType); } function inferFromObjectTypes(source, target) { var _a, _b; @@ -72071,11 +72048,9 @@ function createTypeChecker(host) { /*ignoreErrors*/ true ); - if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) - return void 0; + if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) return void 0; const declaration = symbol.valueDeclaration; - if (declaration === void 0) - return void 0; + if (declaration === void 0) return void 0; const type = tryGetTypeFromEffectiveTypeNode(declaration); if (type) { const name = tryGetNameFromType(type); @@ -72159,8 +72134,7 @@ function createTypeChecker(host) { duplicate = true; } }); - if (!duplicate) - count++; + if (!duplicate) count++; } } } @@ -72367,8 +72341,7 @@ function createTypeChecker(host) { function getTypeOfDestructuredProperty(type, name) { var _a; const nameType = getLiteralTypeFromPropertyName(name); - if (!isTypeUsableAsPropertyName(nameType)) - return errorType; + if (!isTypeUsableAsPropertyName(nameType)) return errorType; const text = getPropertyNameFromType(nameType); return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.type) || errorType; } @@ -72382,8 +72355,7 @@ function createTypeChecker(host) { )) || errorType; } function includeUndefinedInIndexSignature(type) { - if (!type) - return type; + if (!type) return type; return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type; } function getTypeOfDestructuredSpreadExpression(type) { @@ -73682,7 +73654,7 @@ function createTypeChecker(host) { if (!hasDefaultClause) { return caseType; } - const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, getRegularTypeOfLiteralType(extractUnitType(t))))); + const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, t.flags & 32768 /* Undefined */ ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t))))); return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]); } function narrowTypeByTypeName(type, typeName) { @@ -74133,7 +74105,7 @@ function createTypeChecker(host) { function parameterInitializerContainsUndefined(declaration) { const links = getNodeLinks(declaration); if (links.parameterInitializerContainsUndefined === void 0) { - if (!pushTypeResolution(declaration, 9 /* ParameterInitializerContainsUndefined */)) { + if (!pushTypeResolution(declaration, 8 /* ParameterInitializerContainsUndefined */)) { reportCircularityError(declaration.symbol); return true; } @@ -74142,7 +74114,7 @@ function createTypeChecker(host) { reportCircularityError(declaration.symbol); return true; } - links.parameterInitializerContainsUndefined = containsUndefined; + links.parameterInitializerContainsUndefined ?? (links.parameterInitializerContainsUndefined = containsUndefined); } return links.parameterInitializerContainsUndefined; } @@ -74169,6 +74141,9 @@ function createTypeChecker(host) { return contextualType && !isGenericType(contextualType); } function getNarrowableTypeForReference(type, reference, checkMode) { + if (isNoInferType(type)) { + type = type.baseType; + } const substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode)); return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type; } @@ -74187,6 +74162,248 @@ function createTypeChecker(host) { return false; }); } + function markLinkedReferences(location, hint, propSymbol, parentType) { + if (!canCollectSymbolAliasAccessabilityData) { + return; + } + if (location.flags & 33554432 /* Ambient */) { + return; + } + switch (hint) { + case 1 /* Identifier */: + return markIdentifierAliasReferenced(location); + case 2 /* Property */: + return markPropertyAliasReferenced(location, propSymbol, parentType); + case 3 /* ExportAssignment */: + return markExportAssignmentAliasReferenced(location); + case 4 /* Jsx */: + return markJsxAliasReferenced(location); + case 5 /* AsyncFunction */: + return markAsyncFunctionAliasReferenced(location); + case 6 /* ExportImportEquals */: + return markImportEqualsAliasReferenced(location); + case 7 /* ExportSpecifier */: + return markExportSpecifierAliasReferenced(location); + case 8 /* Decorator */: + return markDecoratorAliasReferenced(location); + case 0 /* Unspecified */: { + if (isIdentifier(location) && (isExpressionNode(location) || isShorthandPropertyAssignment(location.parent) || isImportEqualsDeclaration(location.parent) && location.parent.moduleReference === location) && shouldMarkIdentifierAliasReferenced(location)) { + if (isPropertyAccessOrQualifiedName(location.parent)) { + const left = isPropertyAccessExpression(location.parent) ? location.parent.expression : location.parent.left; + if (left !== location) return; + } + markIdentifierAliasReferenced(location); + return; + } + if (isPropertyAccessOrQualifiedName(location)) { + let topProp = location; + while (isPropertyAccessOrQualifiedName(topProp)) { + if (isPartOfTypeNode(topProp)) return; + topProp = topProp.parent; + } + return markPropertyAliasReferenced(location); + } + if (isExportAssignment(location)) { + return markExportAssignmentAliasReferenced(location); + } + if (isJsxOpeningLikeElement(location) || isJsxOpeningFragment(location)) { + return markJsxAliasReferenced(location); + } + if (isImportEqualsDeclaration(location)) { + if (isInternalModuleImportEqualsDeclaration(location) || checkExternalImportOrExportDeclaration(location)) { + return markImportEqualsAliasReferenced(location); + } + return; + } + if (isExportSpecifier(location)) { + return markExportSpecifierAliasReferenced(location); + } + if (isFunctionLikeDeclaration(location) || isMethodSignature(location)) { + markAsyncFunctionAliasReferenced(location); + } + if (!compilerOptions.emitDecoratorMetadata) { + return; + } + if (!canHaveDecorators(location) || !hasDecorators(location) || !location.modifiers || !nodeCanBeDecorated(legacyDecorators, location, location.parent, location.parent.parent)) { + return; + } + return markDecoratorAliasReferenced(location); + } + default: + Debug.assertNever(hint, `Unhandled reference hint: ${hint}`); + } + } + function markIdentifierAliasReferenced(location) { + const symbol = getResolvedSymbol(location); + if (symbol && symbol !== argumentsSymbol && symbol !== unknownSymbol && !isThisInTypeQuery(location)) { + markAliasReferenced(symbol, location); + } + } + function markPropertyAliasReferenced(location, propSymbol, parentType) { + const left = isPropertyAccessExpression(location) ? location.expression : location.left; + if (isThisIdentifier(left) || !isIdentifier(left)) { + return; + } + const parentSymbol = getResolvedSymbol(left); + if (!parentSymbol || parentSymbol === unknownSymbol) { + return; + } + if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location)) { + markAliasReferenced(parentSymbol, location); + return; + } + const leftType = parentType || checkExpressionCached(left); + if (isTypeAny(leftType) || leftType === silentNeverType) { + markAliasReferenced(parentSymbol, location); + return; + } + let prop = propSymbol; + if (!prop && !parentType) { + const right = isPropertyAccessExpression(location) ? location.name : location.right; + const lexicallyScopedSymbol = isPrivateIdentifier(right) && lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right); + const assignmentKind = getAssignmentTargetKind(location); + const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(location) ? getWidenedType(leftType) : leftType); + prop = isPrivateIdentifier(right) ? lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(apparentType, lexicallyScopedSymbol) || void 0 : getPropertyOfType(apparentType, right.escapedText); + } + if (!(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && location.parent.kind === 306 /* EnumMember */))) { + markAliasReferenced(parentSymbol, location); + } + return; + } + function markExportAssignmentAliasReferenced(location) { + if (isIdentifier(location.expression)) { + const id = location.expression; + const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName( + id, + -1 /* All */, + /*ignoreErrors*/ + true, + /*dontResolveAlias*/ + true, + location + )); + if (sym) { + markAliasReferenced(sym, id); + } + } + } + function markJsxAliasReferenced(node) { + if (!getJsxNamespaceContainerForImplicitImport(node)) { + const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.Cannot_find_name_0 : void 0; + const jsxFactoryNamespace = getJsxNamespace(node); + const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node; + let jsxFactorySym; + if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { + jsxFactorySym = resolveName( + jsxFactoryLocation, + jsxFactoryNamespace, + 111551 /* Value */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + if (jsxFactorySym) { + jsxFactorySym.isReferenced = -1 /* All */; + if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) { + markAliasSymbolAsReferenced(jsxFactorySym); + } + } + if (isJsxOpeningFragment(node)) { + const file = getSourceFileOfNode(node); + const localJsxNamespace = getLocalJsxNamespace(file); + if (localJsxNamespace) { + resolveName( + jsxFactoryLocation, + localJsxNamespace, + 111551 /* Value */, + jsxFactoryRefErr, + /*isUse*/ + true + ); + } + } + } + return; + } + function markAsyncFunctionAliasReferenced(location) { + if (languageVersion < 2 /* ES2015 */) { + if (getFunctionFlags(location) & 2 /* Async */) { + const returnTypeNode = getEffectiveReturnTypeNode(location); + markTypeNodeAsReferenced(returnTypeNode); + } + } + } + function markImportEqualsAliasReferenced(location) { + if (hasSyntacticModifier(location, 32 /* Export */)) { + markExportAsReferenced(location); + } + } + function markExportSpecifierAliasReferenced(location) { + if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) { + const exportedName = location.propertyName || location.name; + const symbol = resolveName( + exportedName, + exportedName.escapedText, + 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + } else { + const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); + if (!target || getSymbolFlags(target) & 111551 /* Value */) { + markExportAsReferenced(location); + markIdentifierAliasReferenced(location.propertyName || location.name); + } + } + return; + } + } + function markDecoratorAliasReferenced(node) { + if (compilerOptions.emitDecoratorMetadata) { + const firstDecorator = find(node.modifiers, isDecorator); + if (!firstDecorator) { + return; + } + checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); + switch (node.kind) { + case 263 /* ClassDeclaration */: + const constructor = getFirstConstructorWithBody(node); + if (constructor) { + for (const parameter of constructor.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + } + break; + case 177 /* GetAccessor */: + case 178 /* SetAccessor */: + const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; + const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); + markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); + break; + case 174 /* MethodDeclaration */: + for (const parameter of node.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); + break; + case 172 /* PropertyDeclaration */: + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); + break; + case 169 /* Parameter */: + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); + const containingSignature = node.parent; + for (const parameter of containingSignature.parameters) { + markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); + } + markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); + break; + } + } + } function markAliasReferenced(symbol, location) { if (!canCollectSymbolAliasAccessabilityData) { return; @@ -74204,12 +74421,81 @@ function createTypeChecker(host) { ) & (111551 /* Value */ | 1048576 /* ExportValue */)) { if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) { markAliasSymbolAsReferenced(symbol); - } else { - markConstEnumAliasAsReferenced(symbol); } } } } + function markAliasSymbolAsReferenced(symbol) { + Debug.assert(canCollectSymbolAliasAccessabilityData); + const links = getSymbolLinks(symbol); + if (!links.referenced) { + links.referenced = true; + const node = getDeclarationOfAliasSymbol(symbol); + if (!node) return Debug.fail(); + if (isInternalModuleImportEqualsDeclaration(node)) { + if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) { + const left = getFirstIdentifier(node.moduleReference); + markIdentifierAliasReferenced(left); + } + } + } + } + function markExportAsReferenced(node) { + const symbol = getSymbolOfDeclaration(node); + const target = resolveAlias(symbol); + if (target) { + const markAlias = target === unknownSymbol || getSymbolFlags( + symbol, + /*excludeTypeOnlyMeanings*/ + true + ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); + if (markAlias) { + markAliasSymbolAsReferenced(symbol); + } + } + } + function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { + if (!typeName) return; + const rootName = getFirstIdentifier(typeName); + const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; + const rootSymbol = resolveName( + rootName, + rootName.escapedText, + meaning, + /*nameNotFoundMessage*/ + void 0, + /*isUse*/ + true + ); + if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { + if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { + markAliasSymbolAsReferenced(rootSymbol); + } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { + const diag2 = error2(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); + const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration2); + if (aliasDeclaration) { + addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); + } + } + } + } + function markTypeNodeAsReferenced(node) { + markEntityNameOrEntityExpressionAsReference( + node && getEntityNameFromTypeNode(node), + /*forDecoratorMetadata*/ + false + ); + } + function markDecoratorMedataDataTypeNodeAsReferenced(node) { + const entityName = getEntityNameForDecoratorMetadata(node); + if (entityName && isEntityName(entityName)) { + markEntityNameOrEntityExpressionAsReference( + entityName, + /*forDecoratorMetadata*/ + true + ); + } + } function getNarrowedTypeOfSymbol(symbol, location, checkMode) { var _a; const type = getTypeOfSymbol(symbol, checkMode); @@ -74272,18 +74558,12 @@ function createTypeChecker(host) { } return type; } - function checkIdentifier(node, checkMode) { - if (isThisInTypeQuery(node)) { - return checkThisExpression(node); - } - const symbol = getResolvedSymbol(node); - if (symbol === unknownSymbol) { - return errorType; - } + function checkIdentifierCalculateNodeCheckFlags(node, symbol) { + if (isThisInTypeQuery(node)) return; if (symbol === argumentsSymbol) { if (isInPropertyInitializerOrClassStaticBlock(node)) { error2(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers); - return errorType; + return; } let container = getContainingFunction(node); if (container) { @@ -74302,17 +74582,14 @@ function createTypeChecker(host) { } } } - return getTypeOfSymbol(symbol); - } - if (shouldMarkIdentifierAliasReferenced(node)) { - markAliasReferenced(symbol, node); + return; } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } - let declaration = localOrExportSymbol.valueDeclaration; + const declaration = localOrExportSymbol.valueDeclaration; if (declaration && localOrExportSymbol.flags & 32 /* Class */) { if (isClassLike(declaration) && declaration.name !== node) { let container = getThisContainer( @@ -74339,6 +74616,27 @@ function createTypeChecker(host) { } } checkNestedBlockScopedBinding(node, symbol); + } + function checkIdentifier(node, checkMode) { + if (isThisInTypeQuery(node)) { + return checkThisExpression(node); + } + const symbol = getResolvedSymbol(node); + if (symbol === unknownSymbol) { + return errorType; + } + checkIdentifierCalculateNodeCheckFlags(node, symbol); + if (symbol === argumentsSymbol) { + if (isInPropertyInitializerOrClassStaticBlock(node)) { + return errorType; + } + return getTypeOfSymbol(symbol); + } + if (shouldMarkIdentifierAliasReferenced(node)) { + markLinkedReferences(node, 1 /* Identifier */); + } + const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); + let declaration = localOrExportSymbol.valueDeclaration; let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node, checkMode); const assignmentKind = getAssignmentTargetKind(node); if (assignmentKind) { @@ -74705,8 +75003,7 @@ function createTypeChecker(host) { let inAsyncFunction = false; if (!isCallExpression2) { while (container && container.kind === 219 /* ArrowFunction */) { - if (hasSyntacticModifier(container, 1024 /* Async */)) - inAsyncFunction = true; + if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; container = getSuperContainer( container, /*stopOnFunctions*/ @@ -74714,8 +75011,7 @@ function createTypeChecker(host) { ); needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */; } - if (container && hasSyntacticModifier(container, 1024 /* Async */)) - inAsyncFunction = true; + if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true; } let nodeCheckFlag = 0; if (!container || !isLegalUsageOfSuperExpression(container)) { @@ -74926,12 +75222,10 @@ function createTypeChecker(host) { const parent2 = declaration.parent.parent; const name = declaration.propertyName || declaration.name; const parentType = getContextualTypeForVariableLikeDeclaration(parent2, contextFlags) || parent2.kind !== 208 /* BindingElement */ && parent2.initializer && checkDeclarationInitializer(parent2, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */); - if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) - return void 0; + if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0; if (parent2.name.kind === 207 /* ArrayBindingPattern */) { const index = indexOfNode(declaration.parent.elements, declaration); - if (index < 0) - return void 0; + if (index < 0) return void 0; return getContextualTypeForElementExpression(parentType, index); } const nameType = getLiteralTypeFromPropertyName(name); @@ -74942,8 +75236,7 @@ function createTypeChecker(host) { } function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) { const parentType = isExpression(declaration.parent) && getContextualType2(declaration.parent, contextFlags); - if (!parentType) - return void 0; + if (!parentType) return void 0; return getTypeOfPropertyOfContextualType(parentType, getSymbolOfDeclaration(declaration).escapedName); } function getContextualTypeForInitializerExpression(node, contextFlags) { @@ -75009,7 +75302,31 @@ function createTypeChecker(host) { if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) { contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator)); } - return node.asteriskToken ? contextualReturnType : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); + if (node.asteriskToken) { + const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator); + const yieldType = (iterationTypes == null ? void 0 : iterationTypes.yieldType) ?? silentNeverType; + const returnType = getContextualType2(node, contextFlags) ?? silentNeverType; + const nextType = (iterationTypes == null ? void 0 : iterationTypes.nextType) ?? unknownType; + const generatorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + false + ); + if (isAsyncGenerator) { + const asyncGeneratorType = createGeneratorType( + yieldType, + returnType, + nextType, + /*isAsyncGenerator*/ + true + ); + return getUnionType([generatorType, asyncGeneratorType]); + } + return generatorType; + } + return getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator); } } return void 0; @@ -75240,8 +75557,7 @@ function createTypeChecker(host) { return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration); } function getContextualTypeForThisPropertyAssignment(binaryExpression) { - if (!binaryExpression.symbol) - return getTypeOfExpression(binaryExpression.left); + if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left); if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); if (annotated) { @@ -75462,60 +75778,70 @@ function createTypeChecker(host) { return false; } function discriminateContextualTypeByObjectMembers(node, contextualType) { - return getMatchingUnionConstituentForObjectLiteral(contextualType, node) || discriminateTypeByDiscriminableItems( - contextualType, - concatenate( - map( - filter(node.properties, (p) => { - if (!p.symbol) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + return getCachedType(key) ?? setCachedType( + key, + getMatchingUnionConstituentForObjectLiteral(contextualType, node) ?? discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => { + if (!p.symbol) { + return false; + } + if (p.kind === 303 /* PropertyAssignment */) { + return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); + } + if (p.kind === 304 /* ShorthandPropertyAssignment */) { + return isDiscriminantProperty(contextualType, p.symbol.escapedName); + } return false; - } - if (p.kind === 303 /* PropertyAssignment */) { - return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); - } - if (p.kind === 304 /* ShorthandPropertyAssignment */) { - return isDiscriminantProperty(contextualType, p.symbol.escapedName); - } - return false; - }), - (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] + }), + (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) ), - map( - filter(getPropertiesOfType(contextualType), (s) => { - var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); - }), - (s) => [() => undefinedType, s.escapedName] - ) - ), - isTypeAssignableTo + isTypeAssignableTo + ) ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const key = `D${getNodeId(node)},${getTypeId(contextualType)}`; + const cached = getCachedType(key); + if (cached) return cached; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return discriminateTypeByDiscriminableItems( - contextualType, - concatenate( - map( - filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), - (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + return setCachedType( + key, + discriminateTypeByDiscriminableItems( + contextualType, + concatenate( + map( + filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))), + (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName] + ), + map( + filter(getPropertiesOfType(contextualType), (s) => { + var _a; + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + }), + (s) => [() => undefinedType, s.escapedName] + ) ), - map( - filter(getPropertiesOfType(contextualType), (s) => { - var _a; - if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { - return false; - } - const element = node.parent.parent; - if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { - return false; - } - return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); - }), - (s) => [() => undefinedType, s.escapedName] - ) - ), - isTypeAssignableTo + isTypeAssignableTo + ) ); } function getApparentTypeOfContextualType(node, contextFlags) { @@ -75791,8 +76117,7 @@ function createTypeChecker(host) { if (typeParams) { const inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context)); libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs)); - } else - libraryManagedAttributeType = intrinsicClassAttribs; + } else libraryManagedAttributeType = intrinsicClassAttribs; apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType); } const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context); @@ -75949,7 +76274,7 @@ function createTypeChecker(host) { } function checkGrammarRegularExpressionLiteral(node) { const sourceFile = getSourceFileOfNode(node); - if (!hasParseDiagnostics(sourceFile)) { + if (!hasParseDiagnostics(sourceFile) && !node.isUnterminated) { let lastError; scanner2 ?? (scanner2 = createScanner( 99 /* ESNext */, @@ -76164,8 +76489,7 @@ function createTypeChecker(host) { const links = getSymbolLinks(symbol); if (!links.immediateTarget) { const node = getDeclarationOfAliasSymbol(symbol); - if (!node) - return Debug.fail(); + if (!node) return Debug.fail(); links.immediateTarget = getTargetOfAliasDeclaration( node, /*dontRecursivelyResolve*/ @@ -76340,12 +76664,9 @@ function createTypeChecker(host) { return createObjectLiteralType(); function createObjectLiteralType() { const indexInfos = []; - if (hasComputedStringProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType)); - if (hasComputedNumberProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType)); - if (hasComputedSymbolProperty) - indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType)); + if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType)); + if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType)); + if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType)); const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos); result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { @@ -76585,8 +76906,7 @@ function createTypeChecker(host) { if (!links.resolvedSymbol) { const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node); if (!isErrorType(intrinsicElementsType)) { - if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) - return Debug.fail(); + if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail(); const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText; const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName); if (intrinsicProp) { @@ -76628,11 +76948,7 @@ function createTypeChecker(host) { } const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; - const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0; - const specifier = file == null ? void 0 : file.imports[jsxImportIndex]; - if (specifier) { - Debug.assert(nodeIsSynthesized(specifier) && specifier.text === runtimeImportSpecifier, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`); - } + const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier); const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location); const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0; if (links) { @@ -76798,8 +77114,7 @@ function createTypeChecker(host) { } function getJsxElementClassTypeAt(location) { const type = getJsxType(JsxNames.ElementClass, location); - if (isErrorType(type)) - return void 0; + if (isErrorType(type)) return void 0; return type; } function getJsxElementTypeAt(location) { @@ -76813,14 +77128,11 @@ function createTypeChecker(host) { } function getJsxElementTypeTypeAt(location) { const ns = getJsxNamespaceAt(location); - if (!ns) - return void 0; + if (!ns) return void 0; const sym = getJsxElementTypeSymbol(ns); - if (!sym) - return void 0; + if (!sym) return void 0; const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); - if (!type || isErrorType(type)) - return void 0; + if (!type || isErrorType(type)) return void 0; return type; } function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { @@ -76858,42 +77170,7 @@ function createTypeChecker(host) { checkGrammarJsxElement(node); } checkJsxPreconditions(node); - if (!getJsxNamespaceContainerForImplicitImport(node)) { - const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.Cannot_find_name_0 : void 0; - const jsxFactoryNamespace = getJsxNamespace(node); - const jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node; - let jsxFactorySym; - if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { - jsxFactorySym = resolveName( - jsxFactoryLocation, - jsxFactoryNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - /*isUse*/ - true - ); - } - if (jsxFactorySym) { - jsxFactorySym.isReferenced = -1 /* All */; - if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) { - markAliasSymbolAsReferenced(jsxFactorySym); - } - } - if (isJsxOpeningFragment(node)) { - const file = getSourceFileOfNode(node); - const localJsxNamespace = getLocalJsxNamespace(file); - if (localJsxNamespace) { - resolveName( - jsxFactoryLocation, - localJsxNamespace, - 111551 /* Value */, - jsxFactoryRefErr, - /*isUse*/ - true - ); - } - } - } + markLinkedReferences(node, 4 /* Jsx */); if (isNodeOpeningLikeElement) { const jsxOpeningLikeNode = node; const sig = getResolvedSignature(jsxOpeningLikeNode); @@ -77324,7 +77601,13 @@ function createTypeChecker(host) { } else { if (isAnyLike) { if (isIdentifier(left) && parentSymbol) { - markAliasReferenced(parentSymbol, node); + markLinkedReferences( + node, + 2 /* Property */, + /*propSymbol*/ + void 0, + leftType + ); } return isErrorType(apparentType) ? errorType : apparentType; } @@ -77337,9 +77620,7 @@ function createTypeChecker(host) { node.kind === 166 /* QualifiedName */ ); } - if (isIdentifier(left) && parentSymbol && (getIsolatedModules(compilerOptions) || !(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && node.parent.kind === 306 /* EnumMember */)) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) { - markAliasReferenced(parentSymbol, node); - } + markLinkedReferences(node, 2 /* Property */, prop, leftType); let propType; if (!prop) { const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0; @@ -77613,8 +77894,7 @@ function createTypeChecker(host) { } function getSuggestionForSymbolNameLookup(symbols, name, meaning) { const symbol = getSymbol2(symbols, name, meaning); - if (symbol) - return symbol; + if (symbol) return symbol; let candidates; if (symbols === globals) { const primitives = mapDefined( @@ -78238,8 +78518,7 @@ function createTypeChecker(host) { for (const sig of callSignatures) { const firstparam = getTypeAtPosition(sig, 0); const signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */); - if (!length(signaturesOfParam)) - continue; + if (!length(signaturesOfParam)) continue; for (const paramSig of signaturesOfParam) { hasFirstParamSignatures = true; if (hasEffectiveRestParameter(paramSig)) { @@ -78496,8 +78775,7 @@ function createTypeChecker(host) { return callLike; } function isPromiseResolveArityError(node) { - if (!isCallExpression(node) || !isIdentifier(node.expression)) - return false; + if (!isCallExpression(node) || !isIdentifier(node.expression)) return false; const symbol = resolveName( node.expression, node.expression.escapedText, @@ -78515,8 +78793,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ); - if (!globalPromiseSymbol) - return false; + if (!globalPromiseSymbol) return false; const constructorSymbol = getSymbolAtLocation( decl.parent.parent.expression, /*ignoreErrors*/ @@ -78543,10 +78820,8 @@ function createTypeChecker(host) { closestSignature = sig; } max = Math.max(max, maxParameter); - if (minParameter < args.length && minParameter > maxBelow) - maxBelow = minParameter; - if (args.length < maxParameter && maxParameter < minAbove) - minAbove = maxParameter; + if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter; + if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter; } const hasRestParameter2 = some(signatures, hasEffectiveRestParameter); const parameterRange = hasRestParameter2 ? min2 : min2 < max ? min2 + "-" + max : min2; @@ -79344,8 +79619,7 @@ function createTypeChecker(host) { const importNode = getSymbolLinks(apparentType.symbol).originatingImport; if (importNode && !isImportCall(importNode)) { const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); - if (!sigs || !sigs.length) - return; + if (!sigs || !sigs.length) return; addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead)); } } @@ -79551,8 +79825,13 @@ function createTypeChecker(host) { if (cached && cached !== resolvingSignature && !candidatesOutArray) { return cached; } + const saveResolutionStart = resolutionStart; + if (!cached) { + resolutionStart = resolutionTargets.length; + } links.resolvedSignature = resolvingSignature; let result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */); + resolutionStart = saveResolutionStart; if (result !== resolvingSignature) { if (links.resolvedSignature !== resolvingSignature) { result = links.resolvedSignature; @@ -79568,10 +79847,8 @@ function createTypeChecker(host) { } const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0; if (func) { - if (getJSDocClassTag(node)) - return true; - if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) - return false; + if (getJSDocClassTag(node)) return true; + if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false; const symbol = getSymbolOfDeclaration(func); return !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size); } @@ -79716,8 +79993,7 @@ function createTypeChecker(host) { return returnType; } function checkDeprecatedSignature(signature, node) { - if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) - return; + if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) return; if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) { const suggestionNode = getDeprecatedSuggestionNode(node); const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node)); @@ -79748,8 +80024,7 @@ function createTypeChecker(host) { } } function isSymbolOrSymbolForCall(node) { - if (!isCallExpression(node)) - return false; + if (!isCallExpression(node)) return false; let left = node.expression; if (isPropertyAccessExpression(left) && left.name.escapedText === "for") { left = left.expression; @@ -79879,8 +80154,7 @@ function createTypeChecker(host) { )) { return false; } - if (!isIdentifier(node.expression)) - return Debug.fail(); + if (!isIdentifier(node.expression)) return Debug.fail(); const resolvedRequire = resolveName( node.expression, node.expression.escapedText, @@ -79904,8 +80178,7 @@ function createTypeChecker(host) { return false; } function checkTaggedTemplateExpression(node) { - if (!checkGrammarTaggedTemplateChain(node)) - checkGrammarTypeArguments(node, node.typeArguments); + if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments); if (languageVersion < 2 /* TaggedTemplates */) { checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */); } @@ -80583,8 +80856,7 @@ function createTypeChecker(host) { case 177 /* GetAccessor */: case 178 /* SetAccessor */: { const node = parent2; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node); const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType; @@ -80595,8 +80867,7 @@ function createTypeChecker(host) { } case 172 /* PropertyDeclaration */: { const node = parent2; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const valueType = getTypeOfNode(node); const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent)); const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType; @@ -80661,8 +80932,7 @@ function createTypeChecker(host) { case 178 /* SetAccessor */: case 172 /* PropertyDeclaration */: { const node = parent2; - if (!isClassLike(node.parent)) - break; + if (!isClassLike(node.parent)) break; const targetType = getParentTypeOfClassElement(node); const targetParam = createParameter2("target", targetType); const keyType = getClassElementPropertyKeyType(node); @@ -80802,12 +81072,9 @@ function createTypeChecker(host) { returnType = getUnionType(types, 2 /* Subtype */); } if (returnType || yieldType || nextType) { - if (yieldType) - reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); - if (returnType) - reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); - if (nextType) - reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); + if (yieldType) reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */); + if (returnType) reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */); + if (nextType) reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */); if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) { const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType( @@ -80824,15 +81091,12 @@ function createTypeChecker(host) { returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync); } } - if (yieldType) - yieldType = getWidenedType(yieldType); - if (returnType) - returnType = getWidenedType(returnType); - if (nextType) - nextType = getWidenedType(nextType); + if (yieldType) yieldType = getWidenedType(yieldType); + if (returnType) returnType = getWidenedType(returnType); + if (nextType) nextType = getWidenedType(nextType); } if (isGenerator) { - return createGeneratorReturnType( + return createGeneratorType( yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, @@ -80842,7 +81106,7 @@ function createTypeChecker(host) { return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType; } } - function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) { + function createGeneratorType(yieldType, returnType, nextType, isAsyncGenerator) { const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver; const globalGeneratorType = resolver.getGlobalGeneratorType( /*reportErrors*/ @@ -80911,8 +81175,7 @@ function createTypeChecker(host) { void 0 ); } - if (nextType) - pushIfUnique(nextTypes, nextType); + if (nextType) pushIfUnique(nextTypes, nextType); }); return { yieldTypes, nextTypes }; } @@ -81041,19 +81304,16 @@ function createTypeChecker(host) { return void 0; } const functionFlags = getFunctionFlags(func); - if (functionFlags !== 0 /* Normal */) - return void 0; + if (functionFlags !== 0 /* Normal */) return void 0; let singleReturn; if (func.body && func.body.kind !== 241 /* Block */) { singleReturn = func.body; } else { const bailedEarly = forEachReturnStatement(func.body, (returnStatement) => { - if (singleReturn || !returnStatement.expression) - return true; + if (singleReturn || !returnStatement.expression) return true; singleReturn = returnStatement.expression; }); - if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) - return void 0; + if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return void 0; } return checkIfExpressionRefinesAnyParameter(func, singleReturn); } @@ -81064,8 +81324,7 @@ function createTypeChecker(host) { true ); const returnType = checkExpressionCached(expr); - if (!(returnType.flags & 16 /* Boolean */)) - return void 0; + if (!(returnType.flags & 16 /* Boolean */)) return void 0; return forEach(func.parameters, (param, i) => { const initType = getTypeOfSymbol(param.symbol); if (!initType || initType.flags & 16 /* Boolean */ || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) { @@ -81087,8 +81346,7 @@ function createTypeChecker(host) { ); const trueCondition = createFlowNode(32 /* TrueCondition */, expr, antecedent); const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition); - if (trueType2 === initType) - return void 0; + if (trueType2 === initType) return void 0; const falseCondition = createFlowNode(64 /* FalseCondition */, expr, antecedent); const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition); return falseSubtype.flags & 131072 /* Never */ ? trueType2 : void 0; @@ -82196,12 +82454,10 @@ function createTypeChecker(host) { const sourceText = sf.text; const start = skipTrivia(sourceText, left.pos); const isInDiag2657 = sf.parseDiagnostics.some((diag2) => { - if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) - return false; + if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false; return textSpanContainsPosition(diag2, start); }); - if (!isInDiag2657) - error2(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); + if (!isInDiag2657) error2(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects); } return rightType; default: @@ -82358,8 +82614,7 @@ function createTypeChecker(host) { const isRightNaN = isGlobalNaN(skipParentheses(right2)); if (isLeftNaN || isRightNaN) { const err = error2(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */)); - if (isLeftNaN && isRightNaN) - return; + if (isLeftNaN && isRightNaN) return; const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */) : ""; const location = isLeftNaN ? right2 : left2; const expression = skipParentheses(location); @@ -82388,8 +82643,7 @@ function createTypeChecker(host) { function checkYieldExpression(node) { addLazyDiagnostic(checkYieldExpressionGrammar); const func = getContainingFunction(node); - if (!func) - return anyType; + if (!func) return anyType; const functionFlags = getFunctionFlags(func); if (!(functionFlags & 1 /* Generator */)) { return anyType; @@ -82475,6 +82729,10 @@ function createTypeChecker(host) { texts.push(span.literal.text); types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType); } + const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value; + if (evaluated) { + return getFreshTypeOfLiteralType(getStringLiteralType(evaluated)); + } if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType2( node, /*contextFlags*/ @@ -82482,8 +82740,7 @@ function createTypeChecker(host) { ) || unknownType, isTemplateLiteralContextualType)) { return getTemplateLiteralType(texts, types); } - const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value; - return evaluated ? getFreshTypeOfLiteralType(getStringLiteralType(evaluated)) : stringType; + return stringType; } function isTemplateLiteralContextualType(type) { return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */)); @@ -82761,8 +83018,7 @@ function createTypeChecker(host) { } function getUniqueTypeParameterName(typeParameters, baseName) { let len = baseName.length; - while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) - len--; + while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) len--; const s = baseName.slice(0, len); for (let index = 1; true; index++) { const augmentedName = s + index; @@ -83235,7 +83491,7 @@ function createTypeChecker(host) { const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType; const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType; const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType; - const generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); + const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */)); return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode); } function checkClassForDuplicateDeclarations(node) { @@ -83381,8 +83637,7 @@ function createTypeChecker(host) { } } function checkPropertyDeclaration(node) { - if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name); checkVariableLikeDeclaration(node); setNodeLinksForPrivateIdentifierScope(node); if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) { @@ -83396,8 +83651,7 @@ function createTypeChecker(host) { return checkPropertyDeclaration(node); } function checkMethodDeclaration(node) { - if (!checkGrammarMethod(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name); if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") { error2(node.name, Diagnostics.Class_constructor_may_not_be_a_generator); } @@ -83432,8 +83686,7 @@ function createTypeChecker(host) { } function checkConstructorDeclaration(node) { checkSignatureDeclaration(node); - if (!checkGrammarConstructorTypeParameters(node)) - checkGrammarConstructorTypeAnnotation(node); + if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node); checkSourceElement(node.body); const symbol = getSymbolOfDeclaration(node); const firstDeclaration = getDeclarationOfKind(symbol, node.kind); @@ -83508,8 +83761,7 @@ function createTypeChecker(host) { checkSourceElement(node.body); setNodeLinksForPrivateIdentifierScope(node); function checkAccessorDeclarationDiagnostics() { - if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) - checkGrammarComputedPropertyName(node.name); + if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name); checkDecorators(node); checkSignatureDeclaration(node); if (node.kind === 177 /* GetAccessor */) { @@ -83631,11 +83883,9 @@ function createTypeChecker(host) { } function getTypeArgumentConstraint(node) { const typeReferenceNode = tryCast(node.parent, isTypeReferenceType); - if (!typeReferenceNode) - return void 0; + if (!typeReferenceNode) return void 0; const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReferenceNode); - if (!typeParameters) - return void 0; + if (!typeParameters) return void 0; const constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]); return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments2(typeReferenceNode, typeParameters))); } @@ -84216,10 +84466,7 @@ function createTypeChecker(host) { } function createAwaitedTypeIfNeeded(type) { if (isAwaitedTypeNeeded(type)) { - const awaitedType = tryCreateAwaitedType(type); - if (awaitedType) { - return awaitedType; - } + return tryCreateAwaitedType(type) ?? type; } Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like."); return type; @@ -84306,7 +84553,7 @@ function createTypeChecker(host) { return; } } else { - markTypeNodeAsReferenced(returnTypeNode); + markLinkedReferences(node, 5 /* AsyncFunction */); if (isErrorType(returnType)) { return; } @@ -84430,8 +84677,7 @@ function createTypeChecker(host) { return; } const decoratorSignature = getDecoratorCallSignature(node); - if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) - return; + if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) return; let headMessage; const expectedReturnType = decoratorSignature.resolvedReturnType; switch (node.parent.kind) { @@ -84491,49 +84737,6 @@ function createTypeChecker(host) { voidType ); } - function markTypeNodeAsReferenced(node) { - markEntityNameOrEntityExpressionAsReference( - node && getEntityNameFromTypeNode(node), - /*forDecoratorMetadata*/ - false - ); - } - function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) { - if (!typeName) - return; - const rootName = getFirstIdentifier(typeName); - const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; - const rootSymbol = resolveName( - rootName, - rootName.escapedText, - meaning, - /*nameNotFoundMessage*/ - void 0, - /*isUse*/ - true - ); - if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) { - if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) { - markAliasSymbolAsReferenced(rootSymbol); - } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) { - const diag2 = error2(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled); - const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration2); - if (aliasDeclaration) { - addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName))); - } - } - } - } - function markDecoratorMedataDataTypeNodeAsReferenced(node) { - const entityName = getEntityNameForDecoratorMetadata(node); - if (entityName && isEntityName(entityName)) { - markEntityNameOrEntityExpressionAsReference( - entityName, - /*forDecoratorMetadata*/ - true - ); - } - } function getEntityNameForDecoratorMetadata(node) { if (node) { switch (node.kind) { @@ -84613,42 +84816,7 @@ function createTypeChecker(host) { } } } - if (compilerOptions.emitDecoratorMetadata) { - checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */); - switch (node.kind) { - case 263 /* ClassDeclaration */: - const constructor = getFirstConstructorWithBody(node); - if (constructor) { - for (const parameter of constructor.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - } - break; - case 177 /* GetAccessor */: - case 178 /* SetAccessor */: - const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */; - const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind); - markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor)); - break; - case 174 /* MethodDeclaration */: - for (const parameter of node.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node)); - break; - case 172 /* PropertyDeclaration */: - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node)); - break; - case 169 /* Parameter */: - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node)); - const containingSignature = node.parent; - for (const parameter of containingSignature.parameters) { - markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter)); - } - markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature)); - break; - } - } + markLinkedReferences(node, 8 /* Decorator */); for (const modifier of node.modifiers) { if (isDecorator(modifier)) { checkDecorator(modifier); @@ -84918,13 +85086,11 @@ function createTypeChecker(host) { } function checkUnusedTypeParameters(node, addDiagnostic) { const declarations = getSymbolOfDeclaration(node).declarations; - if (!declarations || last(declarations) !== node) - return; + if (!declarations || last(declarations) !== node) return; const typeParameters = getEffectiveTypeParameterDeclarations(node); const seenParentsWithEveryUnused = /* @__PURE__ */ new Set(); for (const typeParameter of typeParameters) { - if (!isTypeParameterUnused(typeParameter)) - continue; + if (!isTypeParameterUnused(typeParameter)) continue; const name = idText(typeParameter.name); const { parent: parent2 } = typeParameter; if (parent2.kind !== 195 /* InferType */ && parent2.typeParameters.every(isTypeParameterUnused)) { @@ -85018,8 +85184,7 @@ function createTypeChecker(host) { unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused) ); } else { - for (const unused of unuseds) - errorUnusedLocal(unused, idText(unused.name), addDiagnostic); + for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic); } }); unusedDestructures.forEach(([bindingPattern, bindingElements]) => { @@ -85231,8 +85396,7 @@ function createTypeChecker(host) { } } function checkCollisionsForDeclarationName(node, name) { - if (!name) - return; + if (!name) return; checkCollisionWithRequireExportsInGeneratedCode(node, name); checkCollisionWithGlobalPromiseInGeneratedCode(node, name); recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name); @@ -85252,8 +85416,7 @@ function createTypeChecker(host) { } const symbol = getSymbolOfDeclaration(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { - if (!isIdentifier(node.name)) - return Debug.fail(); + if (!isIdentifier(node.name)) return Debug.fail(); const localDeclarationSymbol = resolveName( node, node.name.escapedText, @@ -85492,8 +85655,7 @@ function createTypeChecker(host) { forEach(node.declarations, checkSourceElement); } function checkVariableStatement(node) { - if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) - checkGrammarForDisallowedBlockScopedVariableStatement(node); + if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node); checkVariableDeclarationList(node.declarationList); } function checkExpressionStatement(node) { @@ -85511,8 +85673,7 @@ function createTypeChecker(host) { checkSourceElement(node.elseStatement); } function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) { - if (!strictNullChecks) - return; + if (!strictNullChecks) return; bothHelper(condExpr, body); function bothHelper(condExpr2, body2) { condExpr2 = skipParentheses(condExpr2); @@ -85537,8 +85698,7 @@ function createTypeChecker(host) { return; } const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression); - if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) - return; + if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return; const callSignatures = getSignaturesOfType(type, 0 /* Call */); const isPromise = !!getAwaitedTypeOfPromise(type); if (callSignatures.length === 0 && !isPromise) { @@ -85646,10 +85806,8 @@ function createTypeChecker(host) { checkExpression(node.initializer); } } - if (node.condition) - checkTruthinessExpression(node.condition); - if (node.incrementor) - checkExpression(node.incrementor); + if (node.condition) checkTruthinessExpression(node.condition); + if (node.incrementor) checkExpression(node.incrementor); checkSourceElement(node.statement); if (node.locals) { registerForUnusedIdentifiersCheck(node); @@ -85919,8 +86077,7 @@ function createTypeChecker(host) { } const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable"; const cachedTypes2 = getCachedIterationTypes(type, cacheKey); - if (cachedTypes2) - return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2; + if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2; let allIterationTypes; for (const constituent of type.types) { const errorOutputContainer = errorNode ? { errors: void 0 } : void 0; @@ -85946,10 +86103,8 @@ function createTypeChecker(host) { return iterationTypes === noIterationTypes ? void 0 : iterationTypes; } function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) { - if (iterationTypes === noIterationTypes) - return noIterationTypes; - if (iterationTypes === anyIterationTypes) - return anyIterationTypes; + if (iterationTypes === noIterationTypes) return noIterationTypes; + if (iterationTypes === anyIterationTypes) return anyIterationTypes; const { yieldType, returnType, nextType } = iterationTypes; if (errorNode) { getGlobalAwaitedSymbol( @@ -86337,8 +86492,7 @@ function createTypeChecker(host) { ); } function checkBreakOrContinueStatement(node) { - if (!checkGrammarStatementInAmbientContext(node)) - checkGrammarBreakOrContinueStatement(node); + if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node); } function unwrapReturnType(returnType, functionFlags) { const isGenerator = !!(functionFlags & 1 /* Generator */); @@ -86570,8 +86724,7 @@ function createTypeChecker(host) { const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0; const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0; for (const info of indexInfos) { - if (info === checkInfo) - continue; + if (info === checkInfo) continue; const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0; const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0); if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) { @@ -86602,8 +86755,7 @@ function createTypeChecker(host) { } function checkUnmatchedJSDocParameters(node) { const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag); - if (!length(jsdocParameters)) - return; + if (!length(jsdocParameters)) return; const isJs = isInJSFile(node); const parameters = /* @__PURE__ */ new Set(); const excludedParameters = /* @__PURE__ */ new Set(); @@ -86760,11 +86912,9 @@ function createTypeChecker(host) { } } function checkClassExpressionExternalHelpers(node) { - if (node.name) - return; + if (node.name) return; const parent2 = walkUpOuterExpressions(node); - if (!isNamedEvaluationSource(parent2)) - return; + if (!isNamedEvaluationSource(parent2)) return; const willTransformESDecorators = !legacyDecorators && languageVersion < 99 /* ClassAndClassElementDecorators */; let location; if (willTransformESDecorators && classOrConstructorParameterIsDecorated( @@ -87124,81 +87274,79 @@ function createTypeChecker(host) { var _a, _b, _c, _d, _e; const baseProperties = getPropertiesOfType(baseType); const notImplementedInfo = /* @__PURE__ */ new Map(); - basePropertyCheck: - for (const baseProperty of baseProperties) { - const base = getTargetSymbol(baseProperty); - if (base.flags & 4194304 /* Prototype */) { - continue; + basePropertyCheck: for (const baseProperty of baseProperties) { + const base = getTargetSymbol(baseProperty); + if (base.flags & 4194304 /* Prototype */) { + continue; + } + const baseSymbol = getPropertyOfObjectType(type, base.escapedName); + if (!baseSymbol) { + continue; + } + const derived = getTargetSymbol(baseSymbol); + const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); + Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); + if (derived === base) { + const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { + for (const otherBaseType of getBaseTypes(type)) { + if (otherBaseType === baseType) continue; + const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName); + const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); + if (derivedElsewhere && derivedElsewhere !== base) { + continue basePropertyCheck; + } + } + const baseTypeName = typeToString(baseType); + const typeName = typeToString(type); + const basePropertyName = symbolToString(baseProperty); + const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName); + notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties }); } - const baseSymbol = getPropertyOfObjectType(type, base.escapedName); - if (!baseSymbol) { + } else { + const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); + if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { continue; } - const derived = getTargetSymbol(baseSymbol); - const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base); - Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); - if (derived === base) { - const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) { - for (const otherBaseType of getBaseTypes(type)) { - if (otherBaseType === baseType) - continue; - const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName); - const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2); - if (derivedElsewhere && derivedElsewhere !== base) { - continue basePropertyCheck; - } - } - const baseTypeName = typeToString(baseType); - const typeName = typeToString(type); - const basePropertyName = symbolToString(baseProperty); - const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName); - notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties }); - } - } else { - const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived); - if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) { + let errorMessage; + const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; + const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; + if (basePropertyFlags && derivedPropertyFlags) { + if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { continue; } - let errorMessage; - const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */; - const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */; - if (basePropertyFlags && derivedPropertyFlags) { - if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) { - continue; - } - const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; - const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; - if (overriddenInstanceProperty || overriddenInstanceAccessor) { - const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; - error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); - } else if (useDefineForClassFields) { - const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); - if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { - const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); - const propName = uninitialized.name; - if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { - const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; - error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); - } + const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */; + const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */; + if (overriddenInstanceProperty || overriddenInstanceAccessor) { + const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor; + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type)); + } else if (useDefineForClassFields) { + const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer); + if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) { + const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol)); + const propName = uninitialized.name; + if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) { + const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration; + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType)); } } + } + continue; + } else if (isPrototypeProperty(base)) { + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { continue; - } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { - continue; - } else { - Debug.assert(!!(derived.flags & 98304 /* Accessor */)); - errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } - } else if (base.flags & 98304 /* Accessor */) { - errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; } else { - errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; + Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } - error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); + } else if (base.flags & 98304 /* Accessor */) { + errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function; + } else { + errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function; } + error2(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type)); } + } for (const [errorNode, memberInfo] of notImplementedInfo) { if (length(memberInfo.missedProperties) === 1) { if (isClassExpression(errorNode)) { @@ -87333,8 +87481,7 @@ function createTypeChecker(host) { return !containsUndefinedType(flowType); } function checkInterfaceDeclaration(node) { - if (!checkGrammarModifiers(node)) - checkGrammarInterfaceDeclaration(node); + if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); addLazyDiagnostic(() => { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); @@ -87463,11 +87610,10 @@ function createTypeChecker(host) { /*ignoreErrors*/ true ); - if (!symbol) - return evaluatorResult( - /*value*/ - void 0 - ); + if (!symbol) return evaluatorResult( + /*value*/ + void 0 + ); if (expr.kind === 80 /* Identifier */) { const identifier = expr; if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol( @@ -87913,20 +88059,17 @@ function createTypeChecker(host) { return symbol; } const targetSymbol = resolveAlias(symbol); - if (targetSymbol === unknownSymbol) - return targetSymbol; + if (targetSymbol === unknownSymbol) return targetSymbol; while (symbol.flags & 2097152 /* Alias */) { const target = getImmediateAliasedSymbol(symbol); if (target) { - if (target === targetSymbol) - break; + if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { - if (symbol === targetSymbol) - break; + if (symbol === targetSymbol) break; symbol = target; } } @@ -88014,9 +88157,7 @@ function createTypeChecker(host) { checkGrammarModifiers(node); if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (hasSyntacticModifier(node, 32 /* Export */)) { - markExportAsReferenced(node); - } + markLinkedReferences(node, 6 /* ExportImportEquals */); if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) { const target = resolveAlias(getSymbolOfDeclaration(node)); if (target !== unknownSymbol) { @@ -88114,13 +88255,7 @@ function createTypeChecker(host) { if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error2(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { - if (!node.isTypeOnly && !node.parent.parent.isTypeOnly) { - markExportAsReferenced(node); - } - const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol); - if (!target || getSymbolFlags(target) & 111551 /* Value */) { - checkExpressionCached(node.propertyName || node.name); - } + markLinkedReferences(node, 7 /* ExportSpecifier */); } } else { if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && idText(node.propertyName || node.name) === "default") { @@ -88162,8 +88297,8 @@ function createTypeChecker(host) { node )); if (sym) { + markLinkedReferences(node, 3 /* ExportAssignment */); const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, 111551 /* Value */); - markAliasReferenced(sym, id); if (getSymbolFlags(sym) & 111551 /* Value */) { checkExpressionCached(id); if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) { @@ -88776,8 +88911,7 @@ function createTypeChecker(host) { } switch (location.kind) { case 307 /* SourceFile */: - if (!isExternalModule(location)) - break; + if (!isExternalModule(location)) break; case 267 /* ModuleDeclaration */: copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */); break; @@ -88854,8 +88988,7 @@ function createTypeChecker(host) { let result; let containingClass = getContainingClass(node); while (containingClass) { - if (result = callback(containingClass)) - break; + if (result = callback(containingClass)) break; containingClass = getContainingClass(containingClass); } return result; @@ -89446,14 +89579,11 @@ function createTypeChecker(host) { return target; } function isArgumentsLocalBinding(nodeIn) { - if (isGeneratedIdentifier(nodeIn)) - return false; + if (isGeneratedIdentifier(nodeIn)) return false; const node = getParseTreeNode(nodeIn, isIdentifier); - if (!node) - return false; + if (!node) return false; const parent2 = node.parent; - if (!parent2) - return false; + if (!parent2) return false; const isPropertyName2 = (isPropertyAccessExpression(parent2) || isPropertyAssignment(parent2)) && parent2.name === node; return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol; } @@ -89517,7 +89647,6 @@ function createTypeChecker(host) { if (links.isDeclarationWithCollidingName === void 0) { const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) { - const nodeLinks2 = getNodeLinks(symbol.valueDeclaration); if (resolveName( container.parent, symbol.escapedName, @@ -89528,8 +89657,8 @@ function createTypeChecker(host) { false )) { links.isDeclarationWithCollidingName = true; - } else if (nodeLinks2.flags & 16384 /* CapturedBlockScopedBinding */) { - const isDeclaredInLoop = nodeLinks2.flags & 32768 /* BlockScopedBindingInLoop */; + } else if (hasNodeCheckFlag(symbol.valueDeclaration, 16384 /* CapturedBlockScopedBinding */)) { + const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, 32768 /* BlockScopedBindingInLoop */); const inLoopInitializer = isIterationStatement( container, /*lookInLabeledStatements*/ @@ -89611,6 +89740,9 @@ function createTypeChecker(host) { if (!symbol) { return false; } + const container = getSourceFileOfNode(symbol.valueDeclaration); + const fileSymbol = container && getSymbolOfDeclaration(container); + void resolveExternalModuleSymbol(fileSymbol); const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol)); if (target === unknownSymbol) { return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol); @@ -89645,8 +89777,7 @@ function createTypeChecker(host) { } function isImplementationOfOverload(node) { if (nodeIsPresent(node.body)) { - if (isGetAccessor(node) || isSetAccessor(node)) - return false; + if (isGetAccessor(node) || isSetAccessor(node)) return false; const symbol = getSymbolOfDeclaration(node); const signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node @@ -89660,8 +89791,7 @@ function createTypeChecker(host) { } function declaredParameterTypeContainsUndefined(parameter) { const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter); - if (!typeNode) - return false; + if (!typeNode) return false; const type = getTypeFromTypeNode(typeNode); return containsUndefinedType(type); } @@ -89708,10 +89838,111 @@ function createTypeChecker(host) { function getNodeCheckFlags(node) { var _a; const nodeId = node.id || 0; - if (nodeId < 0 || nodeId >= nodeLinks.length) - return 0; + if (nodeId < 0 || nodeId >= nodeLinks.length) return 0; return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0; } + function hasNodeCheckFlag(node, flag) { + calculateNodeCheckFlagWorker(node, flag); + return !!(getNodeCheckFlags(node) & flag); + } + function calculateNodeCheckFlagWorker(node, flag) { + if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnsotics(getSourceFileOfNode(node), compilerOptions)) { + return; + } + const links = getNodeLinks(node); + if (links.calculatedFlags & flag) { + return; + } + switch (flag) { + case 16 /* SuperInstance */: + case 32 /* SuperStatic */: + return checkSingleSuperExpression(node); + case 128 /* MethodWithSuperPropertyAccessInAsync */: + case 256 /* MethodWithSuperPropertyAssignmentInAsync */: + case 2097152 /* ContainsSuperPropertyInStaticInitializer */: + return checkChildSuperExpressions(node); + case 512 /* CaptureArguments */: + case 8192 /* ContainsCapturedBlockScopeBinding */: + case 65536 /* NeedsLoopOutParameter */: + case 262144 /* ContainsConstructorReference */: + return checkChildIdentifiers(node); + case 536870912 /* ConstructorReference */: + return checkSingleIdentifier(node); + case 4096 /* LoopWithCapturedBlockScopedBinding */: + case 32768 /* BlockScopedBindingInLoop */: + case 16384 /* CapturedBlockScopedBinding */: + return checkContainingBlockScopeBindingUses(node); + default: + return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`); + } + function forEachNodeRecursively(root, cb) { + const rootResult = cb(root, root.parent); + if (rootResult === "skip") return void 0; + if (rootResult) return rootResult; + return forEachChildRecursively(root, cb); + } + function checkSuperExpressions(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */ | 2097152 /* ContainsSuperPropertyInStaticInitializer */; + checkSingleSuperExpression(node2); + return void 0; + } + function checkChildSuperExpressions(node2) { + forEachNodeRecursively(node2, checkSuperExpressions); + } + function checkSingleSuperExpression(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 16 /* SuperInstance */ | 32 /* SuperStatic */; + if (node2.kind === 108 /* SuperKeyword */) { + checkSuperExpression(node2); + } + } + function checkIdentifiers(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 512 /* CaptureArguments */ | 8192 /* ContainsCapturedBlockScopeBinding */ | 65536 /* NeedsLoopOutParameter */ | 262144 /* ContainsConstructorReference */; + checkSingleIdentifier(node2); + return void 0; + } + function checkChildIdentifiers(node2) { + forEachNodeRecursively(node2, checkIdentifiers); + } + function checkSingleIdentifier(node2) { + const nodeLinks2 = getNodeLinks(node2); + nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */ | 16384 /* CapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */; + if (isIdentifier(node2) && isExpressionNode(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) { + const s = getSymbolAtLocation( + node2, + /*ignoreErrors*/ + true + ); + if (s && s !== unknownSymbol) { + checkIdentifierCalculateNodeCheckFlags(node2, s); + } + } + } + function checkBlockScopeBindings(node2) { + const links2 = getNodeLinks(node2); + if (links2.calculatedFlags & flag) return "skip"; + links2.calculatedFlags |= 4096 /* LoopWithCapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */; + checkSingleBlockScopeBinding(node2); + return void 0; + } + function checkContainingBlockScopeBindingUses(node2) { + const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2); + forEachNodeRecursively(scope, checkBlockScopeBindings); + } + function checkSingleBlockScopeBinding(node2) { + checkSingleIdentifier(node2); + if (isComputedPropertyName(node2)) { + checkComputedPropertyName(node2); + } + if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) { + setNodeLinksForPrivateIdentifierScope(node2.parent); + } + } + } function getEnumMemberValue(node) { computeEnumMemberValues(node.parent); return getNodeLinks(node).enumMemberValue ?? evaluatorResult( @@ -89732,7 +89963,15 @@ function createTypeChecker(host) { if (node.kind === 306 /* EnumMember */) { return getEnumMemberValue(node).value; } - const symbol = getNodeLinks(node).resolvedSymbol; + if (!getNodeLinks(node).resolvedSymbol) { + void checkExpressionCached(node); + } + const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName( + node, + 111551 /* Value */, + /*ignoreErrors*/ + true + ) : void 0); if (symbol && symbol.flags & 8 /* EnumMember */) { const member = symbol.valueDeclaration; if (isEnumConst(member.parent)) { @@ -89747,12 +89986,10 @@ function createTypeChecker(host) { function getTypeReferenceSerializationKind(typeNameIn, location) { var _a; const typeName = getParseTreeNode(typeNameIn, isEntityName); - if (!typeName) - return 0 /* Unknown */; + if (!typeName) return 0 /* Unknown */; if (location) { location = getParseTreeNode(location); - if (!location) - return 0 /* Unknown */; + if (!location) return 0 /* Unknown */; } let isTypeOnly = false; if (isQualifiedName(typeName)) { @@ -89867,6 +90104,7 @@ function createTypeChecker(host) { function getSingleReturnExpression(declaration) { let candidateExpr; if (declaration && !nodeIsMissing(declaration.body)) { + if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; const body = declaration.body; if (body && isBlock(body)) { forEachReturnStatement(body, (s) => { @@ -90001,22 +90239,6 @@ function createTypeChecker(host) { } return false; } - function isNonNarrowedBindableName(node) { - if (!hasBindableName(node.parent)) { - return false; - } - const expression = node.expression; - if (!isEntityNameExpression(expression)) { - return true; - } - const type = getTypeOfExpression(expression); - const symbol = getSymbolAtLocation(expression); - if (!symbol) { - return false; - } - const declaredType = getTypeOfSymbol(symbol); - return declaredType === type; - } function literalTypeToNode(type, enclosing, tracker) { const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression( type.symbol, @@ -90026,8 +90248,7 @@ function createTypeChecker(host) { void 0, tracker ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse(); - if (enumResult) - return enumResult; + if (enumResult) return enumResult; const literalValue = type.value; return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue); } @@ -90101,9 +90322,10 @@ function createTypeChecker(host) { const node = getParseTreeNode(nodeIn); return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true; }, - getNodeCheckFlags: (nodeIn) => { + hasNodeCheckFlag: (nodeIn, flag) => { const node = getParseTreeNode(nodeIn); - return node ? getNodeCheckFlags(node) : 0; + if (!node) return false; + return hasNodeCheckFlag(node, flag); }, isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible, @@ -90126,6 +90348,10 @@ function createTypeChecker(host) { return node ? getEnumMemberValue(node) : void 0; }, collectLinkedAliases, + markLinkedReferences: (nodeIn) => { + const node = getParseTreeNode(nodeIn); + return node && markLinkedReferences(node, 0 /* Unspecified */); + }, getReferencedValueDeclaration, getReferencedValueDeclarations, getTypeReferenceSerializationKind, @@ -90136,7 +90362,6 @@ function createTypeChecker(host) { return node && getExternalModuleFileFromDeclaration(node); }, isLiteralConstDeclaration, - isNonNarrowedBindableName, isLateBound: (nodeIn) => { const node = getParseTreeNode(nodeIn, isDeclaration); const symbol = node && getSymbolOfDeclaration(node); @@ -90156,19 +90381,17 @@ function createTypeChecker(host) { if (!sym) { return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker); } + resolveExternalModuleSymbol(sym); return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker); }, isImportRequiredByAugmentation }; function isImportRequiredByAugmentation(node) { const file = getSourceFileOfNode(node); - if (!file.symbol) - return false; + if (!file.symbol) return false; const importTarget = getExternalModuleFileFromDeclaration(node); - if (!importTarget) - return false; - if (importTarget === file) - return false; + if (!importTarget) return false; + if (importTarget === file) return false; const exports2 = getExportsOfModule(file.symbol); for (const s of arrayFrom(exports2.values())) { if (s.mergeId) { @@ -90239,8 +90462,7 @@ function createTypeChecker(host) { if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (!isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (!isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } @@ -90345,8 +90567,7 @@ function createTypeChecker(host) { if (augmentations) { for (const list of augmentations) { for (const augmentation of list) { - if (isGlobalScopeAugmentation(augmentation.parent)) - continue; + if (isGlobalScopeAugmentation(augmentation.parent)) continue; mergeModuleAugmentation(augmentation); } } @@ -90377,39 +90598,40 @@ function createTypeChecker(host) { amalgamatedDuplicates = void 0; } function checkExternalEmitHelpers(location, helpers) { - if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) { + if (compilerOptions.importHelpers) { const sourceFile = getSourceFileOfNode(location); if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */)) { const helpersModule = resolveHelpersModule(sourceFile, location); if (helpersModule !== unknownSymbol) { - const uncheckedHelpers = helpers & ~requestedExternalEmitHelpers; - for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) { - if (uncheckedHelpers & helper) { - for (const name of getHelperNames(helper)) { - if (requestedExternalEmitHelperNames.has(name)) - continue; - requestedExternalEmitHelperNames.add(name); - const symbol = resolveSymbol(getSymbol2(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */)); - if (!symbol) { - error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); - } else if (helper & 524288 /* ClassPrivateFieldGet */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) { - error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); - } - } else if (helper & 1048576 /* ClassPrivateFieldSet */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) { - error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); - } - } else if (helper & 1024 /* SpreadArray */) { - if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) { - error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + const links = getSymbolLinks(helpersModule); + links.requestedExternalEmitHelpers ?? (links.requestedExternalEmitHelpers = 0); + if ((links.requestedExternalEmitHelpers & helpers) !== helpers) { + const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers; + for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) { + if (uncheckedHelpers & helper) { + for (const name of getHelperNames(helper)) { + const symbol = resolveSymbol(getSymbol2(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */)); + if (!symbol) { + error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name); + } else if (helper & 524288 /* ClassPrivateFieldGet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) { + error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4); + } + } else if (helper & 1048576 /* ClassPrivateFieldSet */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) { + error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5); + } + } else if (helper & 1024 /* SpreadArray */) { + if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) { + error2(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3); + } } } } } } + links.requestedExternalEmitHelpers |= helpers; } - requestedExternalEmitHelpers |= helpers; } } } @@ -90469,11 +90691,12 @@ function createTypeChecker(host) { return Debug.fail("Unrecognized helper"); } } - function resolveHelpersModule(node, errorNode) { - if (!externalHelpersModule) { - externalHelpersModule = resolveExternalModule(node, externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; + function resolveHelpersModule(file, errorNode) { + const links = getNodeLinks(file); + if (!links.externalHelpersModule) { + links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol; } - return externalHelpersModule; + return links.externalHelpersModule; } function checkGrammarModifiers(node) { var _a; @@ -90792,8 +91015,7 @@ function createTypeChecker(host) { return false; } function reportObviousModifierErrors(node) { - if (!node.modifiers) - return false; + if (!node.modifiers) return false; const modifier = findFirstIllegalModifier(node); return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here); } @@ -91267,7 +91489,6 @@ function createTypeChecker(host) { return true; } } - return false; } } if (isForOfStatement(forInOrOfStatement) && !(forInOrOfStatement.flags & 65536 /* AwaitContext */) && isIdentifier(forInOrOfStatement.initializer) && forInOrOfStatement.initializer.escapedText === "async") { @@ -91977,6 +92198,20 @@ function createTypeChecker(host) { const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */; return blockScopeKind === 2 /* Const */ || blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */; } + function getJSXRuntimeImportSpecifier(file, specifierText) { + const jsxImportIndex = compilerOptions.importHelpers ? 1 : 0; + const specifier = file == null ? void 0 : file.imports[jsxImportIndex]; + if (specifier) { + Debug.assert(nodeIsSynthesized(specifier) && specifier.text === specifierText, `Expected sourceFile.imports[${jsxImportIndex}] to be the synthesized JSX runtime import`); + } + return specifier; + } + function getImportHelpersImportSpecifier(file) { + Debug.assert(compilerOptions.importHelpers, "Expected importHelpers to be enabled"); + const specifier = file.imports[0]; + Debug.assert(specifier && nodeIsSynthesized(specifier) && specifier.text === "tslib", `Expected sourceFile.imports[0] to be the synthesized tslib import`); + return specifier; + } } function isNotAccessor(declaration) { return !isAccessor(declaration); @@ -92063,8 +92298,7 @@ var SymbolTrackerImpl = class _SymbolTrackerImpl { this.onDiagnosticReported(); return true; } - if (!(symbol.flags & 262144 /* TypeParameter */)) - ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); + if (!(symbol.flags & 262144 /* TypeParameter */)) ((_b = this.context).trackedSymbols ?? (_b.trackedSymbols = [])).push([symbol, enclosingDeclaration, meaning]); } return false; } @@ -92230,8 +92464,7 @@ function visitArrayWorker(nodes, visitor, test, start, count) { function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor = visitNodes2) { context.startLexicalEnvironment(); statements = nodesVisitor(statements, visitor, isStatement, start); - if (ensureUseStrict) - statements = context.factory.ensureUseStrict(statements); + if (ensureUseStrict) statements = context.factory.ensureUseStrict(statements); return factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment()); } function visitParameterList(nodes, visitor, context, nodesVisitor = visitNodes2) { @@ -92254,8 +92487,7 @@ function addDefaultValueAssignmentsIfNeeded(parameters, context) { const parameter = parameters[i]; const updated = addDefaultValueAssignmentIfNeeded(parameter, context); if (result || updated !== parameter) { - if (!result) - result = parameters.slice(0, i); + if (!result) result = parameters.slice(0, i); result[i] = updated; } } @@ -93491,8 +93723,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, function setSourceContent(sourceIndex, content) { enter(); if (content !== null) { - if (!sourcesContent) - sourcesContent = []; + if (!sourcesContent) sourcesContent = []; while (sourcesContent.length < sourceIndex) { sourcesContent.push(null); } @@ -93502,8 +93733,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, } function addName(name) { enter(); - if (!nameToNameIndexMap) - nameToNameIndexMap = /* @__PURE__ */ new Map(); + if (!nameToNameIndexMap) nameToNameIndexMap = /* @__PURE__ */ new Map(); let nameIndex = nameToNameIndexMap.get(name); if (nameIndex === void 0) { nameIndex = names.length; @@ -93578,8 +93808,7 @@ function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, newSourceLine = raw.sourceLine; newSourceCharacter = raw.sourceCharacter; if (map2.names && raw.nameIndex !== void 0) { - if (!nameIndexToNewNameIndexMap) - nameIndexToNewNameIndexMap = []; + if (!nameIndexToNewNameIndexMap) nameIndexToNewNameIndexMap = []; newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex]; if (newNameIndex === void 0) { nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map2.names[raw.nameIndex]); @@ -93749,40 +93978,27 @@ function decodeMappings(mappings) { let hasSource = false; let hasName = false; generatedCharacter += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (generatedCharacter < 0) - return setErrorAndStopIterating("Invalid generatedCharacter found"); + if (hasReportedError()) return stopIterating(); + if (generatedCharacter < 0) return setErrorAndStopIterating("Invalid generatedCharacter found"); if (!isSourceMappingSegmentEnd()) { hasSource = true; sourceIndex += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceIndex < 0) - return setErrorAndStopIterating("Invalid sourceIndex found"); - if (isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); + if (hasReportedError()) return stopIterating(); + if (sourceIndex < 0) return setErrorAndStopIterating("Invalid sourceIndex found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex"); sourceLine += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceLine < 0) - return setErrorAndStopIterating("Invalid sourceLine found"); - if (isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); + if (hasReportedError()) return stopIterating(); + if (sourceLine < 0) return setErrorAndStopIterating("Invalid sourceLine found"); + if (isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine"); sourceCharacter += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (sourceCharacter < 0) - return setErrorAndStopIterating("Invalid sourceCharacter found"); + if (hasReportedError()) return stopIterating(); + if (sourceCharacter < 0) return setErrorAndStopIterating("Invalid sourceCharacter found"); if (!isSourceMappingSegmentEnd()) { hasName = true; nameIndex += base64VLQFormatDecode(); - if (hasReportedError()) - return stopIterating(); - if (nameIndex < 0) - return setErrorAndStopIterating("Invalid nameIndex found"); - if (!isSourceMappingSegmentEnd()) - return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); + if (hasReportedError()) return stopIterating(); + if (nameIndex < 0) return setErrorAndStopIterating("Invalid nameIndex found"); + if (!isSourceMappingSegmentEnd()) return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex"); } } return { value: captureMapping(hasSource, hasName), done }; @@ -93827,11 +94043,9 @@ function decodeMappings(mappings) { let shiftCount = 0; let value = 0; for (; moreDigits; pos++) { - if (pos >= mappings.length) - return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; + if (pos >= mappings.length) return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1; const currentByte = base64FormatDecode(mappings.charCodeAt(pos)); - if (currentByte === -1) - return setError("Invalid character in VLQ"), -1; + if (currentByte === -1) return setError("Invalid character in VLQ"), -1; moreDigits = (currentByte & 32) !== 0; value = value | (currentByte & 31) << shiftCount; shiftCount += 5; @@ -93938,11 +94152,9 @@ function createDocumentPositionMapper(host, map2, mapPath) { if (sourceMappings === void 0) { const lists = []; for (const mapping of getDecodedMappings()) { - if (!isSourceMappedPosition(mapping)) - continue; + if (!isSourceMappedPosition(mapping)) continue; let list = lists[mapping.sourceIndex]; - if (!list) - lists[mapping.sourceIndex] = list = []; + if (!list) lists[mapping.sourceIndex] = list = []; list.push(mapping); } sourceMappings = lists.map((list) => sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition)); @@ -93961,11 +94173,9 @@ function createDocumentPositionMapper(host, map2, mapPath) { } function getGeneratedPosition(loc) { const sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName)); - if (sourceIndex === void 0) - return loc; + if (sourceIndex === void 0) return loc; const sourceMappings2 = getSourceMappings(sourceIndex); - if (!some(sourceMappings2)) - return loc; + if (!some(sourceMappings2)) return loc; let targetIndex = binarySearchKey(sourceMappings2, loc.pos, getSourcePositionOfMapping, compareValues); if (targetIndex < 0) { targetIndex = ~targetIndex; @@ -93978,8 +94188,7 @@ function createDocumentPositionMapper(host, map2, mapPath) { } function getSourcePosition(loc) { const generatedMappings2 = getGeneratedMappings(); - if (!some(generatedMappings2)) - return loc; + if (!some(generatedMappings2)) return loc; let targetIndex = binarySearchKey(generatedMappings2, loc.pos, getGeneratedPositionOfMapping, compareValues); if (targetIndex < 0) { targetIndex = ~targetIndex; @@ -94002,10 +94211,8 @@ function getOriginalNodeId(node) { return node ? getNodeId(node) : 0; } function containsDefaultReference(node) { - if (!node) - return false; - if (!isNamedImports(node) && !isNamedExports(node)) - return false; + if (!node) return false; + if (!isNamedImports(node) && !isNamedExports(node)) return false; return some(node.elements, isNamedDefaultReference); } function isNamedDefaultReference(e) { @@ -94031,8 +94238,7 @@ function getImportNeedsImportStarHelper(node) { if (!bindings) { return false; } - if (!isNamedImports(bindings)) - return false; + if (!isNamedImports(bindings)) return false; let defaultRefCount = 0; for (const binding of bindings.elements) { if (isNamedDefaultReference(binding)) { @@ -94051,8 +94257,8 @@ function collectExternalModuleInfo(context, sourceFile) { const exportSpecifiers = new IdentifierNameMultiMap(); const exportedBindings = []; const uniqueExports = /* @__PURE__ */ new Map(); + const exportedFunctions = /* @__PURE__ */ new Set(); let exportedNames; - let exportedFunctions; let hasExportDefault = false; let exportEquals; let hasExportStarsToExportValues = false; @@ -94112,19 +94318,12 @@ function collectExternalModuleInfo(context, sourceFile) { break; case 262 /* FunctionDeclaration */: if (hasSyntacticModifier(node, 32 /* Export */)) { - exportedFunctions = append(exportedFunctions, node); - if (hasSyntacticModifier(node, 2048 /* Default */)) { - if (!hasExportDefault) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node)); - hasExportDefault = true; - } - } else { - const name = node.name; - if (!uniqueExports.get(idText(name))) { - multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); - uniqueExports.set(idText(name), true); - } - } + addExportedFunctionDeclaration( + node, + /*name*/ + void 0, + hasSyntacticModifier(node, 2048 /* Default */) + ); } break; case 263 /* ClassDeclaration */: @@ -94160,6 +94359,10 @@ function collectExternalModuleInfo(context, sourceFile) { } const decl = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); if (decl) { + if (decl.kind === 262 /* FunctionDeclaration */) { + addExportedFunctionDeclaration(decl, specifier.name, specifier.name.escapedText === "default" /* Default */); + continue; + } multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); } uniqueExports.set(idText(specifier.name), true); @@ -94167,6 +94370,21 @@ function collectExternalModuleInfo(context, sourceFile) { } } } + function addExportedFunctionDeclaration(node, name, isDefault) { + exportedFunctions.add(node); + if (isDefault) { + if (!hasExportDefault) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name ?? context.factory.getDeclarationName(node)); + hasExportDefault = true; + } + } else { + name ?? (name = node.name); + if (!uniqueExports.get(idText(name))) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); + uniqueExports.set(idText(name), true); + } + } + } } function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { @@ -94452,8 +94670,7 @@ function getAllDecoratorsOfProperty(property) { function walkUpLexicalEnvironments(env, cb) { while (env) { const result = cb(env); - if (result !== void 0) - return result; + if (result !== void 0) return result; env = env.previous; } } @@ -94842,16 +95059,12 @@ function flattenArrayBindingOrAssignmentPattern(flattenContext, parent2, pattern } function isSimpleBindingOrAssignmentElement(element) { const target = getTargetOfBindingOrAssignmentElement(element); - if (!target || isOmittedExpression(target)) - return true; + if (!target || isOmittedExpression(target)) return true; const propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(element); - if (propertyName && !isPropertyNameLiteral(propertyName)) - return false; + if (propertyName && !isPropertyNameLiteral(propertyName)) return false; const initializer = getInitializerOfBindingOrAssignmentElement(element); - if (initializer && !isSimpleInlineableExpression(initializer)) - return false; - if (isBindingOrAssignmentPattern(target)) - return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); + if (initializer && !isSimpleInlineableExpression(initializer)) return false; + if (isBindingOrAssignmentPattern(target)) return every(getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement); return isIdentifier(target); } function createDefaultValueCheck(flattenContext, value, defaultValue, location) { @@ -95516,8 +95729,7 @@ function transformTypeScript(context) { return isModifier(node) ? void 0 : visitor(node); } function modifierVisitor(node) { - if (isDecorator(node)) - return void 0; + if (isDecorator(node)) return void 0; if (modifierToFlag(node.kind) & 28895 /* TypeScriptModifier */) { return void 0; } else if (currentNamespace && node.kind === 95 /* ExportKeyword */) { @@ -95665,21 +95877,14 @@ function transformTypeScript(context) { true, /*isStatic*/ true - ))) - facts |= 1 /* HasStaticInitializedProperties */; + ))) facts |= 1 /* HasStaticInitializedProperties */; const extendsClauseElement = getEffectiveBaseTypeNode(node); - if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */) - facts |= 64 /* IsDerivedClass */; - if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) - facts |= 2 /* HasClassOrConstructorParameterDecorators */; - if (childIsDecorated(legacyDecorators, node)) - facts |= 4 /* HasMemberDecorators */; - if (isExportOfNamespace(node)) - facts |= 8 /* IsExportOfNamespace */; - else if (isDefaultExternalModuleExport(node)) - facts |= 32 /* IsDefaultExternalExport */; - else if (isNamedExternalModuleExport(node)) - facts |= 16 /* IsNamedExternalExport */; + if (extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */) facts |= 64 /* IsDerivedClass */; + if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) facts |= 2 /* HasClassOrConstructorParameterDecorators */; + if (childIsDecorated(legacyDecorators, node)) facts |= 4 /* HasMemberDecorators */; + if (isExportOfNamespace(node)) facts |= 8 /* IsExportOfNamespace */; + else if (isDefaultExternalModuleExport(node)) facts |= 32 /* IsDefaultExternalExport */; + else if (isNamedExternalModuleExport(node)) facts |= 16 /* IsNamedExternalExport */; return facts; } function hasTypeScriptClassSyntax(node) { @@ -95876,8 +96081,7 @@ function transformTypeScript(context) { return modifiers; } function getTypeMetadata(node, container) { - if (!legacyDecorators) - return void 0; + if (!legacyDecorators) return void 0; return USE_NEW_TYPE_METADATA_FORMAT ? getNewTypeMetadata(node, container) : getOldTypeMetadata(node, container); } function getOldTypeMetadata(node, container) { @@ -97442,10 +97646,8 @@ function transformClassFields(context) { return fallbackVisitor(node); } function shouldTransformClassElementToWeakMap(node) { - if (shouldTransformPrivateElementsOrClassStaticBlocks) - return true; - if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) - return true; + if (shouldTransformPrivateElementsOrClassStaticBlocks) return true; + if (hasStaticModifier(node) && getInternalEmitFlags(node) & 32 /* TransformPrivateStaticElements */) return true; return false; } function visitMethodOrAccessorDeclaration(node) { @@ -97505,10 +97707,9 @@ function transformClassFields(context) { } } } - function getClassThis() { + function tryGetClassThis() { const lex = getClassLexicalEnvironment(); - const classThis = lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); - return Debug.checkDefined(classThis); + return lex.classThis ?? lex.classConstructor ?? (currentClassContainer == null ? void 0 : currentClassContainer.name); } function transformAutoAccessor(node) { const commentRange = getCommentRange(node); @@ -97536,7 +97737,7 @@ function transformClassFields(context) { setOriginalNode(backingField, node); setEmitFlags(backingField, 3072 /* NoComments */); setSourceMapRange(backingField, sourceMapRange); - const receiver = isStatic(node) ? getClassThis() : factory2.createThis(); + const receiver = isStatic(node) ? tryGetClassThis() ?? factory2.createThis() : factory2.createThis(); const getter = createAccessorPropertyGetRedirector(factory2, node, modifiers, getterName, receiver); setOriginalNode(getter, node); setCommentRange(getter, commentRange); @@ -98102,7 +98303,7 @@ function transformClassFields(context) { var _a; let facts = 0 /* None */; const original = getOriginalNode(node); - if (isClassDeclaration(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { + if (isClassLike(original) && classOrConstructorParameterIsDecorated(legacyDecorators, original)) { facts |= 1 /* ClassWasDecorated */; } if (shouldTransformPrivateElementsOrClassStaticBlocks && (classHasClassThisAssignment(node) || classHasExplicitlyAssignedName(node))) { @@ -98138,7 +98339,7 @@ function transformClassFields(context) { containsInstancePrivateElements || (containsInstancePrivateElements = isPrivateIdentifierClassElementDeclaration(member)); } else if (isPrivateIdentifierClassElementDeclaration(member)) { containsInstancePrivateElements = true; - if (resolver.getNodeCheckFlags(member) & 262144 /* ContainsConstructorReference */) { + if (resolver.hasNodeCheckFlag(member, 262144 /* ContainsConstructorReference */)) { facts |= 2 /* NeedsClassConstructorReference */; } } else if (isPropertyDeclaration(member)) { @@ -98245,7 +98446,7 @@ function transformClassFields(context) { if ((_b = node.emitNode) == null ? void 0 : _b.classThis) { getClassLexicalEnvironment().classThis = node.emitNode.classThis; } - const isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */; + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); const isExport = hasSyntacticModifier(node, 32 /* Export */); const isDefault = hasSyntacticModifier(node, 2048 /* Default */); let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); @@ -98307,15 +98508,14 @@ function transformClassFields(context) { var _a, _b, _c; const isDecoratedClassDeclaration = !!(facts & 1 /* ClassWasDecorated */); const staticPropertiesOrClassStaticBlocks = getStaticPropertiesAndClassStaticBlock(node); - const classCheckFlags = resolver.getNodeCheckFlags(node); - const isClassWithConstructorReference = classCheckFlags & 262144 /* ContainsConstructorReference */; + const isClassWithConstructorReference = resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */); + const requiresBlockScopedVar = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); let temp; function createClassTempVar() { var _a2; if (shouldTransformPrivateElementsOrClassStaticBlocks && ((_a2 = node.emitNode) == null ? void 0 : _a2.classThis)) { return getClassLexicalEnvironment().classConstructor = node.emitNode.classThis; } - const requiresBlockScopedVar = classCheckFlags & 32768 /* BlockScopedBindingInLoop */; const temp2 = factory2.createTempVariable( requiresBlockScopedVar ? addBlockScopedVariable : hoistVariableDeclaration, /*reservedInNestedScopes*/ @@ -98883,7 +99083,7 @@ function transformClassFields(context) { const alreadyTransformed = !!cacheAssignment || isAssignmentExpression(innerExpression) && isGeneratedIdentifier(innerExpression.left); if (!alreadyTransformed && !inlinable && shouldHoist) { const generatedName = factory2.getGeneratedNameForNode(name); - if (resolver.getNodeCheckFlags(name) & 32768 /* BlockScopedBindingInLoop */) { + if (resolver.hasNodeCheckFlag(name, 32768 /* BlockScopedBindingInLoop */)) { addBlockScopedVariable(generatedName); } else { hoistVariableDeclaration(generatedName); @@ -99037,7 +99237,7 @@ function transformClassFields(context) { prefix, suffix ); - if (resolver.getNodeCheckFlags(node) & 32768 /* BlockScopedBindingInLoop */) { + if (resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */)) { addBlockScopedVariable(identifier); } else { hoistVariableDeclaration(identifier); @@ -99132,10 +99332,8 @@ function transformClassFields(context) { } function visitArrayAssignmentElement(node) { if (isArrayBindingOrAssignmentElement(node)) { - if (isSpreadElement(node)) - return visitAssignmentRestElement(node); - if (!isOmittedExpression(node)) - return visitAssignmentElement(node); + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); } return visitEachChild(node, visitor, context); } @@ -99170,12 +99368,9 @@ function transformClassFields(context) { } function visitObjectAssignmentElement(node) { Debug.assertNode(node, isObjectBindingOrAssignmentElement); - if (isSpreadAssignment(node)) - return visitAssignmentRestProperty(node); - if (isShorthandPropertyAssignment(node)) - return visitShorthandAssignmentProperty(node); - if (isPropertyAssignment(node)) - return visitAssignmentProperty(node); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); return visitEachChild(node, visitor, context); } function visitAssignmentPattern(node) { @@ -99281,7 +99476,7 @@ function transformClassFields(context) { } function trySubstituteClassAlias(node) { if (enabledSubstitutions & 1 /* ClassAliases */) { - if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -99534,13 +99729,11 @@ function createRuntimeTypeSerializer(context) { for (let typeNode of types) { typeNode = skipTypeParentheses(typeNode); if (typeNode.kind === 146 /* NeverKeyword */) { - if (isIntersection) - return factory2.createVoidZero(); + if (isIntersection) return factory2.createVoidZero(); continue; } if (typeNode.kind === 159 /* UnknownKeyword */) { - if (!isIntersection) - return factory2.createIdentifier("Object"); + if (!isIntersection) return factory2.createIdentifier("Object"); continue; } if (typeNode.kind === 133 /* AnyKeyword */) { @@ -99764,18 +99957,15 @@ function transformLegacyDecorators(context) { } function hasClassElementWithDecoratorContainingPrivateIdentifierInExpression(node) { for (const member of node.members) { - if (!canHaveDecorators(member)) - continue; + if (!canHaveDecorators(member)) continue; const allDecorators = getAllDecoratorsOfClassElement( member, node, /*useLegacyDecorators*/ true ); - if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) - return true; - if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) - return true; + if (some(allDecorators == null ? void 0 : allDecorators.decorators, decoratorContainsPrivateIdentifierInExpression)) return true; + if (some(allDecorators == null ? void 0 : allDecorators.parameters, parameterDecoratorsContainPrivateIdentifierInExpression)) return true; } return false; } @@ -100153,7 +100343,7 @@ function transformLegacyDecorators(context) { } } function getClassAliasIfNeeded(node) { - if (resolver.getNodeCheckFlags(node) & 262144 /* ContainsConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 262144 /* ContainsConstructorReference */)) { enableSubstitutionForClassAliases(); const classAlias = factory2.createUniqueName(node.name && !isGeneratedIdentifier(node.name) ? idText(node.name) : "default"); classAliases[getOriginalNodeId(node)] = classAlias; @@ -100186,7 +100376,7 @@ function transformLegacyDecorators(context) { } function trySubstituteClassAlias(node) { if (classAliases) { - if (resolver.getNodeCheckFlags(node) & 536870912 /* ConstructorReference */) { + if (resolver.hasNodeCheckFlag(node, 536870912 /* ConstructorReference */)) { const declaration = resolver.getReferencedValueDeclaration(node); if (declaration) { const classAlias = classAliases[declaration.id]; @@ -100472,14 +100662,10 @@ function transformESDecorators(context) { } function getHelperVariableName(node) { let declarationName = node.name && isIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name) : node.name && isPrivateIdentifier(node.name) && !isGeneratedIdentifier(node.name) ? idText(node.name).slice(1) : node.name && isStringLiteral(node.name) && isIdentifierText(node.name.text, 99 /* ESNext */) ? node.name.text : isClassLike(node) ? "class" : "member"; - if (isGetAccessor(node)) - declarationName = `get_${declarationName}`; - if (isSetAccessor(node)) - declarationName = `set_${declarationName}`; - if (node.name && isPrivateIdentifier(node.name)) - declarationName = `private_${declarationName}`; - if (isStatic(node)) - declarationName = `static_${declarationName}`; + if (isGetAccessor(node)) declarationName = `get_${declarationName}`; + if (isSetAccessor(node)) declarationName = `set_${declarationName}`; + if (node.name && isPrivateIdentifier(node.name)) declarationName = `private_${declarationName}`; + if (isStatic(node)) declarationName = `static_${declarationName}`; return "_" + declarationName; } function createHelperVariable(node, suffix) { @@ -101702,10 +101888,8 @@ function transformESDecorators(context) { } function visitArrayAssignmentElement(node) { Debug.assertNode(node, isArrayBindingOrAssignmentElement); - if (isSpreadElement(node)) - return visitAssignmentRestElement(node); - if (!isOmittedExpression(node)) - return visitAssignmentElement(node); + if (isSpreadElement(node)) return visitAssignmentRestElement(node); + if (!isOmittedExpression(node)) return visitAssignmentElement(node); return visitEachChild(node, visitor, context); } function visitAssignmentProperty(node) { @@ -101739,12 +101923,9 @@ function transformESDecorators(context) { } function visitObjectAssignmentElement(node) { Debug.assertNode(node, isObjectBindingOrAssignmentElement); - if (isSpreadAssignment(node)) - return visitAssignmentRestProperty(node); - if (isShorthandPropertyAssignment(node)) - return visitShorthandAssignmentProperty(node); - if (isPropertyAssignment(node)) - return visitAssignmentProperty(node); + if (isSpreadAssignment(node)) return visitAssignmentRestProperty(node); + if (isShorthandPropertyAssignment(node)) return visitShorthandAssignmentProperty(node); + if (isPropertyAssignment(node)) return visitAssignmentProperty(node); return visitEachChild(node, visitor, context); } function visitAssignmentPattern(node) { @@ -102504,7 +102685,7 @@ function transformES2017(context) { hasSuperElementAccess = false; let updated = visitFunctionBody(node.body, visitor, context); const originalMethod = getOriginalNode(node, isFunctionLikeDeclaration); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */; + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) && (getFunctionFlags(originalMethod) & 3 /* AsyncGenerator */) !== 3 /* AsyncGenerator */; if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -102515,9 +102696,9 @@ function transformES2017(context) { updated = factory2.updateBlock(updated, statements); } if (hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(updated, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(updated, asyncSuperHelper); } } @@ -102584,7 +102765,7 @@ function transformES2017(context) { const promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : void 0; const isArrowFunction2 = node.kind === 219 /* ArrowFunction */; const savedLexicalArgumentsBinding = lexicalArgumentsBinding; - const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 512 /* CaptureArguments */) !== 0; + const hasLexicalArguments = resolver.hasNodeCheckFlag(node, 512 /* CaptureArguments */); const captureLexicalArguments = hasLexicalArguments && !lexicalArgumentsBinding; if (captureLexicalArguments) { lexicalArgumentsBinding = factory2.createUniqueName("arguments"); @@ -102639,7 +102820,7 @@ function transformES2017(context) { ) ) ); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); if (capturedSuperProperties.size) { @@ -102658,9 +102839,9 @@ function transformES2017(context) { ); setTextRange(block, node.body); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(block, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(block, asyncSuperHelper); } } @@ -102719,7 +102900,7 @@ function transformES2017(context) { } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -102823,7 +103004,7 @@ function transformES2017(context) { } } function createSuperAccessVariableStatement(factory2, resolver, node, names) { - const hasBinding = (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) !== 0; + const hasBinding = resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */); const accessors = []; names.forEach((_, key) => { const name = unescapeLeadingUnderscores(key); @@ -103918,7 +104099,7 @@ function transformES2018(context) { !!(hierarchyFacts & 1 /* HasLexicalThis */) ) ); - const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (256 /* MethodWithSuperPropertyAssignmentInAsync */ | 128 /* MethodWithSuperPropertyAccessInAsync */); + const emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) || resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); const variableStatement = createSuperAccessVariableStatement(factory2, resolver, node, capturedSuperProperties); @@ -103928,9 +104109,9 @@ function transformES2018(context) { outerStatements.push(returnStatement); const block = factory2.updateBlock(node.body, outerStatements); if (emitSuperHelpers && hasSuperElementAccess) { - if (resolver.getNodeCheckFlags(node) & 256 /* MethodWithSuperPropertyAssignmentInAsync */) { + if (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */)) { addEmitHelper(block, advancedAsyncSuperHelper); - } else if (resolver.getNodeCheckFlags(node) & 128 /* MethodWithSuperPropertyAccessInAsync */) { + } else if (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */)) { addEmitHelper(block, asyncSuperHelper); } } @@ -104063,7 +104244,7 @@ function transformES2018(context) { } function onEmitNode(hint, node, emitCallback) { if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) { - const superContainerFlags = resolver.getNodeCheckFlags(node) & (128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */); + const superContainerFlags = (resolver.hasNodeCheckFlag(node, 128 /* MethodWithSuperPropertyAccessInAsync */) ? 128 /* MethodWithSuperPropertyAccessInAsync */ : 0) | (resolver.hasNodeCheckFlag(node, 256 /* MethodWithSuperPropertyAssignmentInAsync */) ? 256 /* MethodWithSuperPropertyAssignmentInAsync */ : 0); if (superContainerFlags !== enclosingSuperContainerFlags) { const savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags; enclosingSuperContainerFlags = superContainerFlags; @@ -104694,10 +104875,10 @@ function transformESNext(context) { function visitForOfStatement(node) { if (isUsingVariableDeclarationList(node.initializer)) { const forInitializer = node.initializer; - Debug.assertNode(forInitializer, isUsingVariableDeclarationList); - Debug.assert(forInitializer.declarations.length === 1, "ForInitializer may only have one declaration"); - const forDecl = forInitializer.declarations[0]; - Debug.assert(!forDecl.initializer, "ForInitializer may not have an initializer"); + const forDecl = firstOrUndefined(forInitializer.declarations) || factory2.createVariableDeclaration(factory2.createTempVariable( + /*recordTempVariable*/ + void 0 + )); const isAwaitUsing = getUsingKindOfVariableDeclarationList(forInitializer) === 2 /* Async */; const temp = factory2.getGeneratedNameForNode(forDecl.name); const usingVar = factory2.updateVariableDeclaration( @@ -104852,8 +105033,7 @@ function transformESNext(context) { append(statements, hoist(node)); } function hoist(node) { - if (!topLevelStatements) - return node; + if (!topLevelStatements) return node; switch (node.kind) { case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: @@ -105156,10 +105336,8 @@ function getUsingKindOfStatements(statements) { let result = 0 /* None */; for (const statement of statements) { const usingKind = getUsingKind(statement); - if (usingKind === 2 /* Async */) - return 2 /* Async */; - if (usingKind > result) - result = usingKind; + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; } return result; } @@ -105167,10 +105345,8 @@ function getUsingKindOfCaseOrDefaultClauses(clauses) { let result = 0 /* None */; for (const clause of clauses) { const usingKind = getUsingKindOfStatements(clause.statements); - if (usingKind === 2 /* Async */) - return 2 /* Async */; - if (usingKind > result) - result = usingKind; + if (usingKind === 2 /* Async */) return 2 /* Async */; + if (usingKind > result) result = usingKind; } return result; } @@ -106673,8 +106849,7 @@ function transformES2015(context) { } function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { const isDerivedClass = !!extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== 106 /* NullKeyword */; - if (!constructor) - return createDefaultConstructorBody(node, isDerivedClass); + if (!constructor) return createDefaultConstructorBody(node, isDerivedClass); const prologue = []; const statements = []; resumeLexicalEnvironment(); @@ -107774,9 +107949,8 @@ function transformES2015(context) { return createRange(pos, end); } function shouldEmitExplicitInitializerForLetDeclaration(node) { - const flags = resolver.getNodeCheckFlags(node); - const isCapturedInFunction = flags & 16384 /* CapturedBlockScopedBinding */; - const isDeclaredInLoop = flags & 32768 /* BlockScopedBindingInLoop */; + const isCapturedInFunction = resolver.hasNodeCheckFlag(node, 16384 /* CapturedBlockScopedBinding */); + const isDeclaredInLoop = resolver.hasNodeCheckFlag(node, 32768 /* BlockScopedBindingInLoop */); const emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0 || isCapturedInFunction && isDeclaredInLoop && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0; const emitExplicitInitializer = !emittedAsTopLevel && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0 && (!resolver.isDeclarationWithCollidingName(node) || isDeclaredInLoop && !isCapturedInFunction && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0); return emitExplicitInitializer; @@ -108227,7 +108401,7 @@ function transformES2015(context) { return factory2.inlineExpressions(expressions); } function shouldConvertPartOfIterationStatement(node) { - return (resolver.getNodeCheckFlags(node) & 8192 /* ContainsCapturedBlockScopeBinding */) !== 0; + return resolver.hasNodeCheckFlag(node, 8192 /* ContainsCapturedBlockScopeBinding */); } function shouldConvertInitializerOfForStatement(node) { return isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer); @@ -108242,7 +108416,7 @@ function transformES2015(context) { return shouldConvertBodyOfIterationStatement(node) || shouldConvertInitializerOfForStatement(node); } function shouldConvertBodyOfIterationStatement(node) { - return (resolver.getNodeCheckFlags(node) & 4096 /* LoopWithCapturedBlockScopedBinding */) !== 0; + return resolver.hasNodeCheckFlag(node, 4096 /* LoopWithCapturedBlockScopedBinding */); } function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) { if (!state.hoistedLocalVariables) { @@ -108291,10 +108465,8 @@ function transformES2015(context) { const initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : void 0; const bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : void 0; convertedLoopState = outerConvertedLoopState; - if (initializerFunction) - statements.push(initializerFunction.functionDeclaration); - if (bodyFunction) - statements.push(bodyFunction.functionDeclaration); + if (initializerFunction) statements.push(initializerFunction.functionDeclaration); + if (bodyFunction) statements.push(bodyFunction.functionDeclaration); addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState); if (initializerFunction) { statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield)); @@ -108500,10 +108672,8 @@ function transformES2015(context) { const functionName = factory2.createUniqueName("_loop_init"); const containsYield = (node.initializer.transformFlags & 1048576 /* ContainsYield */) !== 0; let emitFlags = 0 /* None */; - if (currentState.containsLexicalThis) - emitFlags |= 16 /* CapturesThis */; - if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) - emitFlags |= 524288 /* AsyncFunctionBody */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */) emitFlags |= 524288 /* AsyncFunctionBody */; const statements = []; statements.push(factory2.createVariableStatement( /*modifiers*/ @@ -108595,14 +108765,11 @@ function transformES2015(context) { /*multiLine*/ true ); - if (isBlock(statement)) - setOriginalNode(loopBody, statement); + if (isBlock(statement)) setOriginalNode(loopBody, statement); const containsYield = (node.statement.transformFlags & 1048576 /* ContainsYield */) !== 0; let emitFlags = 1048576 /* ReuseTempVariableScope */; - if (currentState.containsLexicalThis) - emitFlags |= 16 /* CapturesThis */; - if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) - emitFlags |= 524288 /* AsyncFunctionBody */; + if (currentState.containsLexicalThis) emitFlags |= 16 /* CapturesThis */; + if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0) emitFlags |= 524288 /* AsyncFunctionBody */; const functionDeclaration = factory2.createVariableStatement( /*modifiers*/ void 0, @@ -108798,11 +108965,11 @@ function transformES2015(context) { void 0, name )); - const checkFlags = resolver.getNodeCheckFlags(decl); - if (checkFlags & 65536 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForHead) { + const needsOutParam = resolver.hasNodeCheckFlag(decl, 65536 /* NeedsLoopOutParameter */); + if (needsOutParam || hasCapturedBindingsInForHead) { const outParamName = factory2.createUniqueName("out_" + idText(name)); let flags = 0 /* None */; - if (checkFlags & 65536 /* NeedsLoopOutParameter */) { + if (needsOutParam) { flags |= 1 /* Body */; } if (isForStatement(container)) { @@ -110674,8 +110841,7 @@ function transformGenerators(context) { } function endBlock() { const block = peekBlock(); - if (block === void 0) - return Debug.fail("beginBlock was never called."); + if (block === void 0) return Debug.fail("beginBlock was never called."); const index = blockActions.length; blockActions[index] = 1 /* Close */; blockOffsets[index] = operations ? operations.length : 0; @@ -111509,10 +111675,8 @@ function transformModule(context) { ); } } - if (some(currentModuleInfo.exportedFunctions)) { - for (const f of currentModuleInfo.exportedFunctions) { - appendExportsOfHoistedDeclaration(statements, f); - } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); } append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); addRange(statements, visitNodes2(node.statements, topLevelVisitor, isStatement, statementOffset)); @@ -111829,10 +111993,8 @@ function transformModule(context) { if (some(currentModuleInfo.exportedNames)) { append(statements, factory2.createExpressionStatement(reduceLeft(currentModuleInfo.exportedNames, (prev, nextId) => factory2.createAssignment(factory2.createPropertyAccessExpression(factory2.createIdentifier("exports"), factory2.createIdentifier(idText(nextId))), prev), factory2.createVoidZero()))); } - if (some(currentModuleInfo.exportedFunctions)) { - for (const f of currentModuleInfo.exportedFunctions) { - appendExportsOfHoistedDeclaration(statements, f); - } + for (const f of currentModuleInfo.exportedFunctions) { + appendExportsOfHoistedDeclaration(statements, f); } append(statements, visitNode(currentModuleInfo.externalHelpersImportDeclaration, topLevelVisitor, isStatement)); if (moduleKind === 2 /* AMD */) { @@ -113546,7 +113708,7 @@ function transformSystemModule(context) { if (!moduleInfo.hasExportStarsToExportValues) { return; } - if (!some(moduleInfo.exportedNames) && !some(moduleInfo.exportedFunctions) && moduleInfo.exportSpecifiers.size === 0) { + if (!some(moduleInfo.exportedNames) && moduleInfo.exportedFunctions.size === 0 && moduleInfo.exportSpecifiers.size === 0) { let hasExportDeclarationWithExportClause = false; for (const externalImport of moduleInfo.externalImports) { if (externalImport.kind === 278 /* ExportDeclaration */ && externalImport.exportClause) { @@ -113577,19 +113739,17 @@ function transformSystemModule(context) { ); } } - if (moduleInfo.exportedFunctions) { - for (const f of moduleInfo.exportedFunctions) { - if (hasSyntacticModifier(f, 2048 /* Default */)) { - continue; - } - Debug.assert(!!f.name); - exportedNames.push( - factory2.createPropertyAssignment( - factory2.createStringLiteralFromNode(f.name), - factory2.createTrue() - ) - ); + for (const f of moduleInfo.exportedFunctions) { + if (hasSyntacticModifier(f, 2048 /* Default */)) { + continue; } + Debug.assert(!!f.name); + exportedNames.push( + factory2.createPropertyAssignment( + factory2.createStringLiteralFromNode(f.name), + factory2.createTrue() + ) + ); } const exportedNamesStorageRef = factory2.createUniqueName("exportedNames"); statements.push( @@ -114646,24 +114806,20 @@ function transformSystemModule(context) { function getReferencedDeclaration(name) { if (!isGeneratedIdentifier(name)) { const importDeclaration = resolver.getReferencedImportDeclaration(name); - if (importDeclaration) - return importDeclaration; + if (importDeclaration) return importDeclaration; const valueDeclaration = resolver.getReferencedValueDeclaration(name); - if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) - return valueDeclaration; + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) return valueDeclaration; const declarations = resolver.getReferencedValueDeclarations(name); if (declarations) { for (const declaration of declarations) { - if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) - return declaration; + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) return declaration; } } return valueDeclaration; } } function preventSubstitution(node) { - if (noSubstitution === void 0) - noSubstitution = []; + if (noSubstitution === void 0) noSubstitution = []; noSubstitution[getNodeId(node)] = true; return node; } @@ -115312,7 +115468,7 @@ function createGetIsolatedDeclarationErrors(resolver) { [260 /* VariableDeclaration */]: Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [172 /* PropertyDeclaration */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [171 /* PropertySignature */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, - [167 /* ComputedPropertyName */]: Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations, + [167 /* ComputedPropertyName */]: Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations, [305 /* SpreadAssignment */]: Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations, [304 /* ShorthandPropertyAssignment */]: Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations, [209 /* ArrayLiteralExpression */]: Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations, @@ -115325,6 +115481,9 @@ function createGetIsolatedDeclarationErrors(resolver) { if (heritageClause) { return createDiagnosticForNode(node, Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations); } + if ((isPartOfTypeNode(node) || isTypeQueryNode(node.parent)) && (isEntityName(node) || isEntityNameExpression(node))) { + return createEntityInTypeNodeError(node); + } Debug.type(node); switch (node.kind) { case 177 /* GetAccessor */: @@ -115360,8 +115519,13 @@ function createGetIsolatedDeclarationErrors(resolver) { } } function findNearestDeclaration(node) { - const result = findAncestor(node, (n) => isExportAssignment(n) || (isStatement(n) ? "quit" : isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n))); - return result; + const result = findAncestor(node, (n) => isExportAssignment(n) || isStatement(n) || isVariableDeclaration(n) || isPropertyDeclaration(n) || isParameter(n)); + if (!result) return void 0; + if (isExportAssignment(result)) return result; + if (isReturnStatement(result)) { + return findAncestor(result, (n) => isFunctionLikeDeclaration(n) && !isConstructorDeclaration(n)); + } + return isStatement(result) ? void 0 : result; } function createAccessorTypeError(node) { const { getAccessor, setAccessor } = getAllAccessorDeclarations(node.symbol.declarations, node); @@ -115375,11 +115539,10 @@ function createGetIsolatedDeclarationErrors(resolver) { } return diag2; } - function createObjectLiteralError(node) { - const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + function addParentDeclarationRelatedInfo(node, diag2) { const parentDeclaration = findNearestDeclaration(node); if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( parentDeclaration.name, /*includeTrivia*/ false @@ -115388,30 +115551,19 @@ function createGetIsolatedDeclarationErrors(resolver) { } return diag2; } + function createObjectLiteralError(node) { + const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } function createArrayLiteralError(node) { const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); - const parentDeclaration = findNearestDeclaration(node); - if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( - parentDeclaration.name, - /*includeTrivia*/ - false - ); - addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); - } + addParentDeclarationRelatedInfo(node, diag2); return diag2; } function createReturnTypeError(node) { const diag2 = createDiagnosticForNode(node, errorByDeclarationKind[node.kind]); - const parentDeclaration = findNearestDeclaration(node); - if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( - parentDeclaration.name, - /*includeTrivia*/ - false - ); - addRelatedInfo(diag2, createDiagnosticForNode(parentDeclaration, relatedSuggestionByDeclarationKind[parentDeclaration.kind], targetStr)); - } + addParentDeclarationRelatedInfo(node, diag2); addRelatedInfo(diag2, createDiagnosticForNode(node, relatedSuggestionByDeclarationKind[node.kind])); return diag2; } @@ -115449,11 +115601,20 @@ function createGetIsolatedDeclarationErrors(resolver) { function createClassExpressionError(node) { return createExpressionError(node, Diagnostics.Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations); } + function createEntityInTypeNodeError(node) { + const diag2 = createDiagnosticForNode(node, Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations, getTextOfNode( + node, + /*includeTrivia*/ + false + )); + addParentDeclarationRelatedInfo(node, diag2); + return diag2; + } function createExpressionError(node, diagnosticMessage) { const parentDeclaration = findNearestDeclaration(node); let diag2; if (parentDeclaration) { - const targetStr = isExportAssignment(parentDeclaration) ? "" : getTextOfNode( + const targetStr = isExportAssignment(parentDeclaration) || !parentDeclaration.name ? "" : getTextOfNode( parentDeclaration.name, /*includeTrivia*/ false @@ -115477,19 +115638,20 @@ function createGetIsolatedDeclarationErrors(resolver) { // src/compiler/transformers/declarations.ts function getDeclarationDiagnostics(host, resolver, file) { const compilerOptions = host.getCompilerOptions(); + const files = filter(getSourceFilesToEmit(host, file), isSourceFileNotJson); const result = transformNodes( resolver, host, factory, compilerOptions, - file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJson), + file ? contains(files, file) ? [file] : emptyArray : files, [transformDeclarations], /*allowDtsFiles*/ false ); return result.diagnostics; } -var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; +var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 1 /* AllowUnresolvedNames */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; function transformDeclarations(context) { const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); let getSymbolAccessibilityDiagnostic = throwDiagnostic; @@ -115540,8 +115702,7 @@ function transformDeclarations(context) { }); } function reportInferenceFallback(node) { - if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) - return; + if (!isolatedDeclarations || isSourceFileJS(currentSourceFile)) return; if (isVariableDeclaration(node) && resolver.isExpandoFunctionDeclaration(node)) { reportExpandoFunctionErrors(node); } else { @@ -115559,7 +115720,7 @@ function transformDeclarations(context) { } } } - } else { + } else if (symbolAccessibilityResult.accessibility !== 3 /* NotResolved */) { const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); if (errorInfo) { if (errorInfo.typeName) { @@ -115573,8 +115734,7 @@ function transformDeclarations(context) { return false; } function trackSymbol(symbol, enclosingDeclaration2, meaning) { - if (symbol.flags & 262144 /* TypeParameter */) - return false; + if (symbol.flags & 262144 /* TypeParameter */) return false; const issuedDiagnostic = handleSymbolAccessibilityError(resolver.isSymbolAccessible( symbol, enclosingDeclaration2, @@ -115659,8 +115819,7 @@ function transformDeclarations(context) { let hasNoDefaultLib = false; const bundle = factory2.createBundle( map(node.sourceFiles, (sourceFile) => { - if (sourceFile.isDeclarationFile) - return void 0; + if (sourceFile.isDeclarationFile) return void 0; hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -115779,22 +115938,19 @@ function transformDeclarations(context) { } function getTypeReferences() { return mapDefined(rawTypeReferenceDirectives, (ref) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; return copyFileReferenceAsSynthetic(ref); }); } function getLibReferences() { return mapDefined(rawLibReferenceDirectives, (ref) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; return copyFileReferenceAsSynthetic(ref); }); } function getReferencedFiles(outputFilePath2) { return mapDefined(rawReferencedFiles, ([sourceFile, ref]) => { - if (!ref.preserve) - return void 0; + if (!ref.preserve) return void 0; const file = host.getSourceFileFromReference(sourceFile, ref); if (!file) { return void 0; @@ -115803,8 +115959,7 @@ function transformDeclarations(context) { if (file.isDeclarationFile) { declFileName = file.fileName; } else { - if (isBundledEmit && contains(node.sourceFiles, file)) - return; + if (isBundledEmit && contains(node.sourceFiles, file)) return; const paths = getOutputPathsFor( file, host, @@ -115813,8 +115968,7 @@ function transformDeclarations(context) { ); declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName; } - if (!declFileName) - return void 0; + if (!declFileName) return void 0; const fileName = getRelativePathToDirectoryOrUrl( outputFilePath2, declFileName, @@ -116040,8 +116194,7 @@ function transformDeclarations(context) { return setCommentRange(updated, getCommentRange(original)); } function rewriteModuleSpecifier(parent2, input) { - if (!input) - return void 0; + if (!input) return void 0; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent2.kind !== 267 /* ModuleDeclaration */ && parent2.kind !== 205 /* ImportType */; if (isStringLiteralLike(input)) { if (isBundledEmit) { @@ -116054,8 +116207,7 @@ function transformDeclarations(context) { return input; } function transformImportEqualsDeclaration(decl) { - if (!resolver.isDeclarationVisible(decl)) - return; + if (!resolver.isDeclarationVisible(decl)) return; if (decl.moduleReference.kind === 283 /* ExternalModuleReference */) { const specifier = getExternalModuleImportEqualsDeclarationExpression(decl); return factory2.updateImportEqualsDeclaration( @@ -116184,22 +116336,28 @@ function transformDeclarations(context) { } } function visitDeclarationSubtree(input) { - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; if (isDeclaration(input)) { - if (isDeclarationAndNotVisible(input)) - return; - if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input))) { - if (isolatedDeclarations && isClassDeclaration(input.parent) && isEntityNameExpression(input.name.expression) && resolver.isEntityNameVisible(input.name.expression, input.parent).accessibility === 0 /* Accessible */ && !resolver.isNonNarrowedBindableName(input.name)) { - context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)); + if (isDeclarationAndNotVisible(input)) return; + if (hasDynamicName(input)) { + if (isolatedDeclarations) { + if (isClassDeclaration(input.parent) || isObjectLiteralExpression(input.parent)) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations)); + return; + } else if ( + // Type declarations just need to double-check that the input computed name is an entity name expression + (isInterfaceDeclaration(input.parent) || isTypeLiteralNode(input.parent)) && !isEntityNameExpression(input.name.expression) + ) { + context.addDiagnostic(createDiagnosticForNode(input, Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations)); + return; + } + } else if (!resolver.isLateBound(getParseTreeNode(input)) || !isEntityNameExpression(input.name.expression)) { + return; } - return; } } - if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) - return; - if (isSemicolonClassElement(input)) - return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + if (isSemicolonClassElement(input)) return; let previousEnclosingDeclaration; if (isEnclosingDeclaration(input)) { previousEnclosingDeclaration = enclosingDeclaration; @@ -116211,8 +116369,7 @@ function transformDeclarations(context) { let shouldEnterSuppressNewDiagnosticsContextContext = (input.kind === 187 /* TypeLiteral */ || input.kind === 200 /* MappedType */) && input.parent.kind !== 265 /* TypeAliasDeclaration */; if (isMethodDeclaration(input) || isMethodSignature(input)) { if (hasEffectiveModifier(input, 2 /* Private */)) { - if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) - return; + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; return cleanup(factory2.createPropertyDeclaration( ensureModifiers(input), input.name, @@ -116445,8 +116602,7 @@ function transformDeclarations(context) { )); } case 205 /* ImportType */: { - if (!isLiteralImportTypeNode(input)) - return cleanup(input); + if (!isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory2.updateImportTypeNode( input, factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), @@ -116490,8 +116646,7 @@ function transformDeclarations(context) { if (!isPreservedDeclarationStatement(input)) { return; } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { case 278 /* ExportDeclaration */: { if (isSourceFile(input.parent)) { @@ -116565,11 +116720,9 @@ function transformDeclarations(context) { } function transformTopLevelDeclaration(input) { if (lateMarkedStatements) { - while (orderedRemoveItem(lateMarkedStatements, input)) - ; + while (orderedRemoveItem(lateMarkedStatements, input)) ; } - if (shouldStripInternal(input)) - return; + if (shouldStripInternal(input)) return; switch (input.kind) { case 271 /* ImportEqualsDeclaration */: { return transformImportEqualsDeclaration(input); @@ -116578,12 +116731,9 @@ function transformDeclarations(context) { return transformImportDeclaration(input); } } - if (isDeclaration(input) && isDeclarationAndNotVisible(input)) - return; - if (isJSDocImportTag(input)) - return; - if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) - return; + if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; + if (isJSDocImportTag(input)) return; + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; let previousEnclosingDeclaration; if (isEnclosingDeclaration(input)) { previousEnclosingDeclaration = enclosingDeclaration; @@ -116787,8 +116937,7 @@ function transformDeclarations(context) { if (ctor) { const oldDiag2 = getSymbolAccessibilityDiagnostic; parameterProperties = compact(flatMap(ctor.parameters, (param) => { - if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) - return; + if (!hasSyntacticModifier(param, 31 /* ParameterPropertyModifier */) || shouldStripInternal(param)) return; getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); if (param.name.kind === 80 /* Identifier */) { return preserveJsDoc( @@ -116807,8 +116956,7 @@ function transformDeclarations(context) { function walkBindingPattern(pattern) { let elems; for (const elem of pattern.elements) { - if (isOmittedExpression(elem)) - continue; + if (isOmittedExpression(elem)) continue; if (isBindingPattern(elem.name)) { elems = concatenate(elems, walkBindingPattern(elem.name)); } @@ -116908,8 +117056,7 @@ function transformDeclarations(context) { factory2.createNodeArray(ensureModifiers(input)), input.name, factory2.createNodeArray(mapDefined(input.members, (m) => { - if (shouldStripInternal(m)) - return; + if (shouldStripInternal(m)) return; const enumValue = resolver.getEnumMemberValue(m); const constValue = enumValue == null ? void 0 : enumValue.value; if (isolatedDeclarations && m.initializer && (enumValue == null ? void 0 : enumValue.hasExternalReferences) && // This will be its own compiler error instead, so don't report. @@ -116942,11 +117089,9 @@ function transformDeclarations(context) { } } function transformVariableStatement(input) { - if (!forEach(input.declarationList.declarations, getBindingNameVisible)) - return; + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; const nodes = visitNodes2(input.declarationList.declarations, visitDeclarationSubtree, isVariableDeclaration); - if (!length(nodes)) - return; + if (!length(nodes)) return; const modifiers = factory2.createNodeArray(ensureModifiers(input)); let declList; if (isVarUsing(input.declarationList) || isVarAwaitUsing(input.declarationList)) { @@ -116967,8 +117112,7 @@ function transformDeclarations(context) { return; } if (e.name) { - if (!getBindingNameVisible(e)) - return; + if (!getBindingNameVisible(e)) return; if (isBindingPattern(e.name)) { return recreateBindingPattern(e.name); } else { @@ -116994,7 +117138,7 @@ function transformDeclarations(context) { getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node); } errorNameNode = node.name; - Debug.assert(resolver.isLateBound(getParseTreeNode(node))); + Debug.assert(hasDynamicName(node)); const decl = node; const entityName = decl.name.expression; checkEntityNameVisibility(entityName, enclosingDeclaration); @@ -117162,8 +117306,7 @@ function getTransformers(compilerOptions, customTransformers, emitOnly) { }; } function getScriptTransformers(compilerOptions, customTransformers, emitOnly) { - if (emitOnly) - return emptyArray; + if (emitOnly) return emptyArray; const languageVersion = getEmitScriptTarget(compilerOptions); const moduleKind = getEmitModuleKind(compilerOptions); const useDefineForClassFields = getUseDefineForClassFields(compilerOptions); @@ -117593,28 +117736,24 @@ function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDt } if (includeBuildInfo) { const buildInfoPath = getTsBuildInfoEmitOutputFilePath(options); - if (buildInfoPath) - return action( - { buildInfoPath }, - /*sourceFileOrBundle*/ - void 0 - ); + if (buildInfoPath) return action( + { buildInfoPath }, + /*sourceFileOrBundle*/ + void 0 + ); } } } function getTsBuildInfoEmitOutputFilePath(options) { const configFile = options.configFilePath; - if (!isIncrementalCompilation(options)) - return void 0; - if (options.tsBuildInfoFile) - return options.tsBuildInfoFile; + if (!isIncrementalCompilation(options)) return void 0; + if (options.tsBuildInfoFile) return options.tsBuildInfoFile; const outPath = options.outFile; let buildInfoExtensionLess; if (outPath) { buildInfoExtensionLess = removeFileExtension(outPath); } else { - if (!configFile) - return void 0; + if (!configFile) return void 0; const configFileExtensionLess = removeFileExtension(configFile); buildInfoExtensionLess = options.outDir ? options.rootDir ? resolvePath(options.outDir, getRelativePathFromDirectory( options.rootDir, @@ -117671,8 +117810,7 @@ function getOutputDeclarationFileNameWorker(inputFileName, options, ignoreCase, ); } function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2 = () => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)) { - if (configFile.options.emitDeclarationOnly) - return void 0; + if (configFile.options.emitDeclarationOnly) return void 0; const isJsonFile = fileExtensionIs(inputFileName, ".json" /* Json */); const outputFileName = getOutputJSFileNameWorker(inputFileName, configFile.options, ignoreCase, getCommonSourceDirectory2); return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ? outputFileName : void 0; @@ -117708,12 +117846,10 @@ function getSingleOutputFileNames(configFile, addOutput) { addOutput(buildInfoPath); } function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory2) { - if (isDeclarationFileName(inputFileName)) - return; + if (isDeclarationFileName(inputFileName)) return; const js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); addOutput(js); - if (fileExtensionIs(inputFileName, ".json" /* Json */)) - return; + if (fileExtensionIs(inputFileName, ".json" /* Json */)) return; if (js && configFile.options.sourceMap) { addOutput(`${js}.map`); } @@ -117784,22 +117920,21 @@ function getFirstProjectOutput(configFile, ignoreCase) { } const getCommonSourceDirectory2 = memoize(() => getCommonSourceDirectoryOfConfig(configFile, ignoreCase)); for (const inputFileName of configFile.fileNames) { - if (isDeclarationFileName(inputFileName)) - continue; + if (isDeclarationFileName(inputFileName)) continue; const jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); - if (jsFilePath) - return jsFilePath; - if (fileExtensionIs(inputFileName, ".json" /* Json */)) - continue; + if (jsFilePath) return jsFilePath; + if (fileExtensionIs(inputFileName, ".json" /* Json */)) continue; if (getEmitDeclarations(configFile.options)) { return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory2); } } const buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options); - if (buildInfoPath) - return buildInfoPath; + if (buildInfoPath) return buildInfoPath; return Debug.fail(`project ${configFile.options.configFilePath} expected to have at least one output`); } +function emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) { + return !!forceDtsEmit && !!emitOnly; +} function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, declarationTransformers }, emitOnly, onlyBuildInfo, forceDtsEmit) { var compilerOptions = host.getCompilerOptions(); var sourceMapDataList = compilerOptions.sourceMap || compilerOptions.inlineSourceMap || getAreDeclarationMapsEnabled(compilerOptions) ? [] : void 0; @@ -117838,8 +117973,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla (_f = tracing) == null ? void 0 : _f.pop(); } function emitBuildInfo(buildInfoPath) { - if (!buildInfoPath || targetSourceFile || emitSkipped) - return; + if (!buildInfoPath || targetSourceFile || emitSkipped) return; if (host.isEmitBlocked(buildInfoPath)) { emitSkipped = true; return; @@ -117869,6 +118003,11 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla emitSkipped = true; return; } + (isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : filter(sourceFileOrBundle.sourceFiles, isSourceFileNotJson)).forEach( + (sourceFile) => { + if (compilerOptions.noCheck || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) markLinkedReferences(sourceFile); + } + ); const transform2 = transformNodes( resolver, host, @@ -117910,19 +118049,19 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath) { - if (!sourceFileOrBundle || emitOnly === 0 /* Js */) - return; + if (!sourceFileOrBundle || emitOnly === 0 /* Js */) return; if (!declarationFilePath) { - if (emitOnly || compilerOptions.emitDeclarationOnly) - emitSkipped = true; + if (emitOnly || compilerOptions.emitDeclarationOnly) emitSkipped = true; return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; const filesForEmit = forceDtsEmit ? sourceFiles : filter(sourceFiles, isSourceFileNotJson); const inputListOrBundle = compilerOptions.outFile ? [factory.createBundle(filesForEmit)] : filesForEmit; - if (emitOnly && !getEmitDeclarations(compilerOptions)) { - filesForEmit.forEach(collectLinkedAliases); - } + filesForEmit.forEach((sourceFile) => { + if (emitOnly && !getEmitDeclarations(compilerOptions) || compilerOptions.noCheck || emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) || !canIncludeBindAndCheckDiagnsotics(sourceFile, compilerOptions)) { + collectLinkedAliases(sourceFile); + } + }); const declarationTransform = transformNodes( resolver, host, @@ -118005,6 +118144,13 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla } forEachChild(node, collectLinkedAliases); } + function markLinkedReferences(file) { + forEachChildRecursively(file, (n) => { + if (isImportEqualsDeclaration(n) && !(getSyntacticModifierFlags(n) & 32 /* Export */)) return "skip"; + if (isImportDeclaration(n)) return "skip"; + resolver.markLinkedReferences(n); + }); + } function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform2, printer, mapOptions) { const sourceFileOrBundle = transform2.transformed[0]; const bundle = sourceFileOrBundle.kind === 308 /* Bundle */ ? sourceFileOrBundle : void 0; @@ -118041,8 +118187,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla sourceFile ); if (sourceMappingURL) { - if (!writer.isAtStartOfLine()) - writer.rawWrite(newLine); + if (!writer.isAtStartOfLine()) writer.rawWrite(newLine); sourceMapUrlPos = writer.getTextPos(); writer.writeComment(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); } @@ -118073,8 +118218,7 @@ function emitFiles(resolver, host, targetSourceFile, { scriptTransformers, decla return sourceRoot ? ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot; } function getSourceMapDirectory(mapOptions, filePath, sourceFile) { - if (mapOptions.sourceRoot) - return host.getCommonSourceDirectory(); + if (mapOptions.sourceRoot) return host.getCommonSourceDirectory(); if (mapOptions.mapRoot) { let sourceMapDir = normalizeSlashes(mapOptions.mapRoot); if (sourceFile) { @@ -118138,10 +118282,11 @@ var notImplementedResolver = { isValueAliasDeclaration: notImplemented, isReferencedAliasDeclaration: notImplemented, isTopLevelValueImportEqualsWithEntityName: notImplemented, - getNodeCheckFlags: notImplemented, + hasNodeCheckFlag: notImplemented, isDeclarationVisible: notImplemented, isLateBound: (_node) => false, collectLinkedAliases: notImplemented, + markLinkedReferences: notImplemented, isImplementationOfOverload: notImplemented, requiresAddingImplicitUndefined: notImplemented, isExpandoFunctionDeclaration: notImplemented, @@ -118162,7 +118307,6 @@ var notImplementedResolver = { isArgumentsLocalBinding: notImplemented, getExternalModuleFileFromDeclaration: notImplemented, isLiteralConstDeclaration: notImplemented, - isNonNarrowedBindableName: notImplemented, getJsxFactoryEntity: notImplemented, getJsxFragmentFactoryEntity: notImplemented, isBindingCapturedByNode: notImplemented, @@ -118407,13 +118551,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { return currentLineMap || (currentLineMap = getLineStarts(Debug.checkDefined(currentSourceFile))); } function emit(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit(4 /* Unspecified */, node, parenthesizerRule); } function emitIdentifierName(node) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit( 2 /* IdentifierName */, node, @@ -118422,8 +118564,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { ); } function emitExpression(node, parenthesizerRule) { - if (node === void 0) - return; + if (node === void 0) return; pipelineEmit(1 /* Expression */, node, parenthesizerRule); } function emitJsxAttributeValue(node) { @@ -118503,20 +118644,15 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitSnippetNode(hint, node, snippet); } } - if (hint === 0 /* SourceFile */) - return emitSourceFile(cast(node, isSourceFile)); - if (hint === 2 /* IdentifierName */) - return emitIdentifier(cast(node, isIdentifier)); - if (hint === 6 /* JsxAttributeValue */) - return emitLiteral( - cast(node, isStringLiteral), - /*jsxAttributeEscape*/ - true - ); - if (hint === 3 /* MappedTypeParameter */) - return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); - if (hint === 7 /* ImportTypeNodeAttributes */) - return emitImportTypeNodeAttributes(cast(node, isImportAttributes)); + if (hint === 0 /* SourceFile */) return emitSourceFile(cast(node, isSourceFile)); + if (hint === 2 /* IdentifierName */) return emitIdentifier(cast(node, isIdentifier)); + if (hint === 6 /* JsxAttributeValue */) return emitLiteral( + cast(node, isStringLiteral), + /*jsxAttributeEscape*/ + true + ); + if (hint === 3 /* MappedTypeParameter */) return emitMappedTypeParameter(cast(node, isTypeParameterDeclaration)); + if (hint === 7 /* ImportTypeNodeAttributes */) return emitImportTypeNodeAttributes(cast(node, isImportAttributes)); if (hint === 5 /* EmbeddedStatement */) { Debug.assertNode(node, isEmptyStatement); return emitEmptyStatement( @@ -118935,10 +119071,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { return Debug.fail("SyntheticReferenceExpression should not be printed"); } } - if (isKeyword(node.kind)) - return writeTokenNode(node, writeKeyword); - if (isTokenKind(node.kind)) - return writeTokenNode(node, writePunctuation); + if (isKeyword(node.kind)) return writeTokenNode(node, writeKeyword); + if (isTokenKind(node.kind)) return writeTokenNode(node, writePunctuation); Debug.fail(`Unhandled SyntaxKind: ${Debug.formatSyntaxKind(node.kind)}.`); } function emitMappedTypeParameter(node) { @@ -118971,8 +119105,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (helpers) { for (const helper of helpers) { if (!helper.scoped) { - if (shouldSkip) - continue; + if (shouldSkip) continue; if (shouldBundle) { if (bundledHelpers.get(helper.name)) { continue; @@ -119066,13 +119199,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitComputedPropertyName(node) { - const savedPrivateNameTempFlags = privateNameTempFlags; - const savedReservedMemberNames = reservedPrivateNames; - popPrivateNameGenerationScope(); writePunctuation("["); emitExpression(node.expression, parenthesizer.parenthesizeExpressionOfComputedPropertyName); writePunctuation("]"); - pushPrivateNameGenerationScope(savedPrivateNameTempFlags, savedReservedMemberNames); } function emitTypeParameter(node) { emitModifierList(node, node.modifiers); @@ -119133,15 +119262,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { writeTrailingSemicolon(); } function emitMethodSignature(node) { - pushNameGenerationScope(node); emitModifierList(node, node.modifiers); emit(node.name); emit(node.questionToken); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitMethodDeclaration(node) { emitDecoratorsAndModifiers( @@ -119153,11 +119277,13 @@ function createPrinter(printerOptions = {}, handlers = {}) { emit(node.asteriskToken); emit(node.name); emit(node.questionToken); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitClassStaticBlockDeclaration(node) { writeKeyword("static"); + pushNameGenerationScope(node); emitBlockFunctionBody(node.body); + popNameGenerationScope(node); } function emitConstructor(node) { emitDecoratorsAndModifiers( @@ -119167,7 +119293,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { false ); writeKeyword("constructor"); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitAccessorDeclaration(node) { const pos = emitDecoratorsAndModifiers( @@ -119180,25 +119306,15 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTokenWithComment(token, pos, writeKeyword, node); writeSpace(); emit(node.name); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); } function emitCallSignature(node) { - pushNameGenerationScope(node); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitConstructSignature(node) { - pushNameGenerationScope(node); writeKeyword("new"); writeSpace(); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - emitTypeAnnotation(node.type); - writeTrailingSemicolon(); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitSignatureHead, emitEmptyFunctionBody); } function emitIndexSignature(node) { emitDecoratorsAndModifiers( @@ -119236,14 +119352,17 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTypeArguments(node, node.typeArguments); } function emitFunctionType(node) { - pushNameGenerationScope(node); + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); + } + function emitFunctionTypeHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); writeSpace(); writePunctuation("=>"); + } + function emitFunctionTypeBody(node) { writeSpace(); emit(node.type); - popNameGenerationScope(node); } function emitJSDocFunctionType(node) { writeKeyword("function"); @@ -119264,17 +119383,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { writePunctuation("="); } function emitConstructorType(node) { - pushNameGenerationScope(node); emitModifierList(node, node.modifiers); writeKeyword("new"); writeSpace(); - emitTypeParameters(node, node.typeParameters); - emitParameters(node, node.parameters); - writeSpace(); - writePunctuation("=>"); - writeSpace(); - emit(node.type); - popNameGenerationScope(node); + emitSignatureAndBody(node, emitFunctionTypeHead, emitFunctionTypeBody); } function emitTypeQuery(node) { writeKeyword("typeof"); @@ -119283,16 +119395,13 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTypeArguments(node, node.typeArguments); } function emitTypeLiteral(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); writePunctuation("{"); const flags = getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */); writePunctuation("}"); - popPrivateNameGenerationScope(); + popNameGenerationScope(node); } function emitArrayType(node) { emit(node.elementType, parenthesizer.parenthesizeNonArrayTypeOfPostfixType); @@ -119464,11 +119573,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine, parenthesizer.parenthesizeExpressionForDisallowedComma); } function emitObjectLiteralExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); + pushNameGenerationScope(node); forEach(node.properties, generateMemberNames); const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; if (indentedFlag) { @@ -119480,7 +119585,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (indentedFlag) { decreaseIndent(); } - popPrivateNameGenerationScope(); + popNameGenerationScope(node); } function emitPropertyAccessExpression(node) { emitExpression(node.expression, parenthesizer.parenthesizeLeftSideOfAccess); @@ -119595,7 +119700,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } function emitArrowFunction(node) { emitModifierList(node, node.modifiers); - emitSignatureAndBody(node, emitArrowFunctionHead); + emitSignatureAndBody(node, emitArrowFunctionHead, emitArrowFunctionBody); } function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); @@ -119604,6 +119709,14 @@ function createPrinter(printerOptions = {}, handlers = {}) { writeSpace(); emit(node.equalsGreaterThanToken); } + function emitArrowFunctionBody(node) { + if (isBlock(node.body)) { + emitBlockFunctionBody(node.body); + } else { + writeSpace(); + emitExpression(node.body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); + } + } function emitDeleteExpression(node) { emitTokenWithComment(91 /* DeleteKeyword */, node.pos, writeKeyword, node); writeSpace(); @@ -119659,10 +119772,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { const emitComments2 = state.shouldEmitCommentsStack[state.stackIndex] = shouldEmitComments(node); const emitSourceMaps = state.shouldEmitSourceMapsStack[state.stackIndex] = shouldEmitSourceMaps(node); onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(node); - if (emitComments2) - emitCommentsBeforeNode(node); - if (emitSourceMaps) - emitSourceMapsBeforeNode(node); + if (emitComments2) emitCommentsBeforeNode(node); + if (emitSourceMaps) emitSourceMapsBeforeNode(node); beforeEmitNode(node); } else { state = { @@ -119713,10 +119824,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { const shouldEmitComments2 = state.shouldEmitCommentsStack[state.stackIndex]; const shouldEmitSourceMaps2 = state.shouldEmitSourceMapsStack[state.stackIndex]; afterEmitNode(savedPreserveSourceNewlines); - if (shouldEmitSourceMaps2) - emitSourceMapsAfterNode(node); - if (shouldEmitComments2) - emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); + if (shouldEmitSourceMaps2) emitSourceMapsAfterNode(node); + if (shouldEmitComments2) emitCommentsAfterNode(node, savedContainerPos, savedContainerEnd, savedDeclarationListContainerEnd); onAfterEmitNode == null ? void 0 : onAfterEmitNode(node); state.stackIndex--; } @@ -120022,8 +120131,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return node.kind === 2 /* SingleLineCommentTrivia */ || !!node.hasTrailingNewLine; } function willEmitLeadingNewLine(node) { - if (!currentSourceFile) - return false; + if (!currentSourceFile) return false; const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (leadingCommentRanges) { const parseNode = getParseTreeNode(node); @@ -120031,14 +120139,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } } - if (some(leadingCommentRanges, commentWillEmitNewLine)) - return true; - if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) - return true; + if (some(leadingCommentRanges, commentWillEmitNewLine)) return true; + if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) return true; if (isPartiallyEmittedExpression(node)) { if (node.pos !== node.expression.pos) { - if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) - return true; + if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) return true; } return willEmitLeadingNewLine(node.expression); } @@ -120151,35 +120256,33 @@ function createPrinter(printerOptions = {}, handlers = {}) { emit(node.asteriskToken); writeSpace(); emitIdentifierName(node.name); - emitSignatureAndBody(node, emitSignatureHead); + emitSignatureAndBody(node, emitSignatureHead, emitFunctionBody); + } + function emitSignatureAndBody(node, emitSignatureHead2, emitBody) { + const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; + if (indentedFlag) { + increaseIndent(); + } + pushNameGenerationScope(node); + forEach(node.parameters, generateNames); + emitSignatureHead2(node); + emitBody(node); + popNameGenerationScope(node); + if (indentedFlag) { + decreaseIndent(); + } } - function emitSignatureAndBody(node, emitSignatureHead2) { + function emitFunctionBody(node) { const body = node.body; if (body) { - if (isBlock(body)) { - const indentedFlag = getEmitFlags(node) & 131072 /* Indented */; - if (indentedFlag) { - increaseIndent(); - } - pushNameGenerationScope(node); - forEach(node.parameters, generateNames); - generateNames(node.body); - emitSignatureHead2(node); - emitBlockFunctionBody(body); - popNameGenerationScope(node); - if (indentedFlag) { - decreaseIndent(); - } - } else { - emitSignatureHead2(node); - writeSpace(); - emitExpression(body, parenthesizer.parenthesizeConciseBodyOfArrowFunction); - } + emitBlockFunctionBody(body); } else { - emitSignatureHead2(node); writeTrailingSemicolon(); } } + function emitEmptyFunctionBody(_node) { + writeTrailingSemicolon(); + } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); @@ -120208,6 +120311,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } function emitBlockFunctionBody(body) { + generateNames(body); onBeforeEmitNode == null ? void 0 : onBeforeEmitNode(body); writeSpace(); writePunctuation("{"); @@ -120248,12 +120352,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitClassDeclarationOrExpression(node); } function emitClassDeclarationOrExpression(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); - forEach(node.members, generateMemberNames); emitDecoratorsAndModifiers( node, node.modifiers, @@ -120273,19 +120371,16 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */); writeSpace(); writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); emitList(node, node.members, 129 /* ClassMembers */); + popNameGenerationScope(node); writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } - popPrivateNameGenerationScope(); } function emitInterfaceDeclaration(node) { - pushPrivateNameGenerationScope( - 0 /* Auto */, - /*newReservedMemberNames*/ - void 0 - ); emitDecoratorsAndModifiers( node, node.modifiers, @@ -120299,9 +120394,11 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitList(node, node.heritageClauses, 512 /* HeritageClauses */); writeSpace(); writePunctuation("{"); + pushNameGenerationScope(node); + forEach(node.members, generateMemberNames); emitList(node, node.members, 129 /* InterfaceMembers */); + popNameGenerationScope(node); writePunctuation("}"); - popPrivateNameGenerationScope(); } function emitTypeAliasDeclaration(node) { emitDecoratorsAndModifiers( @@ -120348,8 +120445,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } emit(node.name); let body = node.body; - if (!body) - return writeTrailingSemicolon(); + if (!body) return writeTrailingSemicolon(); while (body && isModuleDeclaration(body)) { writePunctuation("."); emit(body.name); @@ -120917,8 +121013,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []); } function emitTripleSlashDirectivesIfNeeded(node) { - if (node.isDeclarationFile) - emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); + if (node.isDeclarationFile) emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives); } function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs2) { if (hasNoDefaultLib) { @@ -121038,8 +121133,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitNodeWithWriter(node, writer2) { - if (!node) - return; + if (!node) return; const savedWrite = write; write = writer2; emit(node); @@ -121074,10 +121168,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { pos++; } const textRange = { pos: -1, end: -1 }; - if (start === 0) - textRange.pos = modifiers.pos; - if (pos === modifiers.length - 1) - textRange.end = modifiers.end; + if (start === 0) textRange.pos = modifiers.pos; + if (pos === modifiers.length - 1) textRange.end = modifiers.end; if (lastMode === "modifiers" || allowDecorators) { emitNodeListItems( emit, @@ -121682,6 +121774,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { return getLiteralText(node, currentSourceFile, flags); } function pushNameGenerationScope(node) { + privateNameTempFlagsStack.push(privateNameTempFlags); + privateNameTempFlags = 0 /* Auto */; + reservedPrivateNamesStack.push(reservedPrivateNames); if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { return; } @@ -121692,6 +121787,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { + privateNameTempFlags = privateNameTempFlagsStack.pop(); + reservedPrivateNames = reservedPrivateNamesStack.pop(); if (node && getEmitFlags(node) & 1048576 /* ReuseTempVariableScope */) { return; } @@ -121705,16 +121802,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { } reservedNames.add(name); } - function pushPrivateNameGenerationScope(newPrivateNameTempFlags, newReservedMemberNames) { - privateNameTempFlagsStack.push(privateNameTempFlags); - privateNameTempFlags = newPrivateNameTempFlags; - reservedPrivateNamesStack.push(reservedNames); - reservedPrivateNames = newReservedMemberNames; - } - function popPrivateNameGenerationScope() { - privateNameTempFlags = privateNameTempFlagsStack.pop(); - reservedPrivateNames = reservedPrivateNamesStack.pop(); - } function reservePrivateNameInNestedScopes(name) { if (!reservedPrivateNames || reservedPrivateNames === lastOrUndefined(reservedPrivateNamesStack)) { reservedPrivateNames = /* @__PURE__ */ new Set(); @@ -121722,8 +121809,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { reservedPrivateNames.add(name); } function generateNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 241 /* Block */: forEach(node.statements, generateNames); @@ -121808,13 +121894,14 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function generateMemberNames(node) { - if (!node) - return; + if (!node) return; switch (node.kind) { case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: case 177 /* GetAccessor */: case 178 /* SetAccessor */: generateNameIfNeeded(node.name); @@ -121848,7 +121935,28 @@ function createPrinter(printerOptions = {}, handlers = {}) { return isFileLevelUniqueNameInCurrentFile(name, privateName) && !isReservedName(name, privateName) && !generatedNames.has(name); } function isReservedName(name, privateName) { - return privateName ? !!(reservedPrivateNames == null ? void 0 : reservedPrivateNames.has(name)) : !!(reservedNames == null ? void 0 : reservedNames.has(name)); + let set; + let stack; + if (privateName) { + set = reservedPrivateNames; + stack = reservedPrivateNamesStack; + } else { + set = reservedNames; + stack = reservedNamesStack; + } + if (set == null ? void 0 : set.has(name)) { + return true; + } + for (let i = stack.length - 1; i >= 0; i--) { + if (set === stack[i]) { + continue; + } + set = stack[i]; + if (set == null ? void 0 : set.has(name)) { + return true; + } + } + return false; } function isFileLevelUniqueNameInCurrentFile(name, _isPrivate) { return currentSourceFile ? isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true; @@ -122337,8 +122445,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return true; } function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; if (!hasWrittenComment) { emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos); hasWrittenComment = true; @@ -122366,8 +122473,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; if (!writer.isAtStartOfLine()) { writer.writeSpace(" "); } @@ -122387,8 +122493,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { exitComment(); } function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -122397,8 +122502,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; emitPos(commentPos); writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine); emitPos(commentEnd); @@ -122432,8 +122536,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return detachedCommentsInfo !== void 0 && last(detachedCommentsInfo).nodePos === pos; } function forEachLeadingCommentWithoutDetachedComments(cb) { - if (!currentSourceFile) - return; + if (!currentSourceFile) return; const pos = last(detachedCommentsInfo).detachedCommentEndPos; if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); @@ -122459,8 +122562,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitComment(text, lineMap, writer2, commentPos, commentEnd, newLine2) { - if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) - return; + if (!currentSourceFile || !shouldWriteComment(currentSourceFile.text, commentPos)) return; emitPos(commentPos); writeCommentRange(text, lineMap, writer2, commentPos, commentEnd, newLine2); emitPos(commentEnd); @@ -122537,8 +122639,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { emitSourcePos(source, tokenPos); } tokenPos = emitCallback(token, writer2, tokenPos); - if (range) - tokenPos = range.end; + if (range) tokenPos = range.end; if ((emitFlags & 512 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { emitSourcePos(source, tokenPos); } @@ -122740,8 +122841,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi return result !== void 0 ? result || getFileSystemEntriesFromHost(dir, path) : emptyFileSystemEntries; } function getFileSystemEntriesFromHost(dir, path) { - if (rootSymLinkResult && path === rootDirPath) - return rootSymLinkResult; + if (rootSymLinkResult && path === rootDirPath) return rootSymLinkResult; const result = { files: map(host.readDirectory( dir, @@ -122754,8 +122854,7 @@ function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensi ), getBaseNameOfFileName) || emptyArray, directories: host.getDirectories(dir) || emptyArray }; - if (path === rootDirPath) - rootSymLinkResult = result; + if (path === rootDirPath) rootSymLinkResult = result; return result; } } @@ -122842,8 +122941,7 @@ function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedCon watcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath), close: () => { const existing2 = extendedConfigFilesMap.get(extendedConfigFilePath); - if (!existing2 || existing2.projects.size !== 0) - return; + if (!existing2 || existing2.projects.size !== 0) return; existing2.watcher.close(); extendedConfigFilesMap.delete(extendedConfigFilePath); } @@ -122853,13 +122951,11 @@ function updateSharedExtendedConfigFileWatcher(projectPath, options, extendedCon } function clearSharedExtendedConfigFileWatcher(projectPath, extendedConfigFilesMap) { extendedConfigFilesMap.forEach((watcher) => { - if (watcher.projects.delete(projectPath)) - watcher.close(); + if (watcher.projects.delete(projectPath)) watcher.close(); }); } function cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3) { - if (!extendedConfigCache.delete(extendedConfigFilePath)) - return; + if (!extendedConfigCache.delete(extendedConfigFilePath)) return; extendedConfigCache.forEach(({ extendedResult }, key) => { var _a; if ((_a = extendedResult.extendedSourceFiles) == null ? void 0 : _a.some((extendedFile) => toPath3(extendedFile) === extendedConfigFilePath)) { @@ -122931,8 +123027,7 @@ function isIgnoredFileFromWildCardWatching({ return true; } fileOrDirectoryPath = newPath; - if (fileOrDirectoryPath === watchedDirPath) - return false; + if (fileOrDirectoryPath === watchedDirPath) return false; if (hasExtension(fileOrDirectoryPath) && !(isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions) || isSupportedScriptKind())) { writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); return true; @@ -122941,13 +123036,10 @@ function isIgnoredFileFromWildCardWatching({ writeLog(`Project: ${configFileName} Detected excluded file: ${fileOrDirectory}`); return true; } - if (!program) - return false; - if (options.outFile || options.outDir) - return false; + if (!program) return false; + if (options.outFile || options.outDir) return false; if (isDeclarationFileName(fileOrDirectoryPath)) { - if (options.declarationDir) - return false; + if (options.declarationDir) return false; } else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) { return false; } @@ -122963,8 +123055,7 @@ function isIgnoredFileFromWildCardWatching({ return realProgram ? !!realProgram.getSourceFileByPath(file) : builderProgram ? builderProgram.getState().fileInfos.has(file) : !!find(program, (rootFile) => toPath3(rootFile) === file); } function isSupportedScriptKind() { - if (!getScriptKind2) - return false; + if (!getScriptKind2) return false; const scriptKind = getScriptKind2(fileOrDirectory); switch (scriptKind) { case 3 /* TS */: @@ -123246,8 +123337,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { const readFileWithCache = (fileName) => { const key = toPath3(fileName); const value = readFileCache.get(key); - if (value !== void 0) - return value !== false ? value : void 0; + if (value !== void 0) return value !== false ? value : void 0; return setReadFileCache(key, fileName); }; const setReadFileCache = (key, fileName) => { @@ -123258,8 +123348,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.readFile = (fileName) => { const key = toPath3(fileName); const value = readFileCache.get(key); - if (value !== void 0) - return value !== false ? value : void 0; + if (value !== void 0) return value !== false ? value : void 0; if (!fileExtensionIs(fileName, ".json" /* Json */) && !isBuildInfoFile(fileName)) { return originalReadFile.call(host, fileName); } @@ -123270,8 +123359,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { const impliedNodeFormat = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : void 0; const forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat); const value = forImpliedNodeFormat == null ? void 0 : forImpliedNodeFormat.get(key); - if (value) - return value; + if (value) return value; const sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile); if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".json" /* Json */))) { sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || /* @__PURE__ */ new Map()).set(key, sourceFile)); @@ -123281,8 +123369,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.fileExists = (fileName) => { const key = toPath3(fileName); const value = fileExistsCache.get(key); - if (value !== void 0) - return value; + if (value !== void 0) return value; const newValue = originalFileExists.call(host, fileName); fileExistsCache.set(key, !!newValue); return newValue; @@ -123310,8 +123397,7 @@ function changeCompilerHostLikeToUseCache(host, toPath3, getSourceFile) { host.directoryExists = (directory) => { const key = toPath3(directory); const value = directoryExistsCache.get(key); - if (value !== void 0) - return value; + if (value !== void 0) return value; const newValue = originalDirectoryExists.call(host, directory); directoryExistsCache.set(key, !!newValue); return newValue; @@ -123553,8 +123639,7 @@ function getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions) { return fileEmitMode === 1 /* CommonJS */ ? 1 /* CommonJS */ : emitModuleKindIsNonNodeESM(fileEmitMode) || fileEmitMode === 200 /* Preserve */ ? 99 /* ESNext */ : void 0; } function getResolutionModeOverride(node, grammarErrorOnNode) { - if (!node) - return void 0; + if (!node) return void 0; if (length(node.elements) !== 1) { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( node, @@ -123563,8 +123648,7 @@ function getResolutionModeOverride(node, grammarErrorOnNode) { return void 0; } const elem = node.elements[0]; - if (!isStringLiteralLike(elem.name)) - return void 0; + if (!isStringLiteralLike(elem.name)) return void 0; if (elem.name.text !== "resolution-mode") { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode( elem.name, @@ -123572,8 +123656,7 @@ function getResolutionModeOverride(node, grammarErrorOnNode) { ); return void 0; } - if (!isStringLiteralLike(elem.value)) - return void 0; + if (!isStringLiteralLike(elem.value)) return void 0; if (elem.value.text !== "import" && elem.value.text !== "require") { grammarErrorOnNode == null ? void 0 : grammarErrorOnNode(elem.value, Diagnostics.resolution_mode_should_be_either_require_or_import); return void 0; @@ -123606,7 +123689,7 @@ function createModuleResolutionLoader(containingFile, redirectedReference, optio }; } function getTypeReferenceResolutionName(entry) { - return !isString(entry) ? toFileNameLowerCase(entry.fileName) : entry; + return !isString(entry) ? entry.fileName : entry; } var typeReferenceResolutionNameAndModeGetter = { getName: getTypeReferenceResolutionName, @@ -123627,8 +123710,7 @@ function createTypeReferenceResolutionLoader(containingFile, redirectedReference }; } function loadWithModeAwareCache(entries, containingFile, redirectedReference, options, containingSourceFile, host, resolutionCache, createLoader) { - if (entries.length === 0) - return emptyArray; + if (entries.length === 0) return emptyArray; const resolutions = []; const cache = /* @__PURE__ */ new Map(); const loader = createLoader(containingFile, redirectedReference, options, host, resolutionCache); @@ -123663,16 +123745,14 @@ function forEachProjectReference(projectReferences, resolvedProjectReferences, c function worker(projectReferences2, resolvedProjectReferences2, parent2) { if (cbRef) { const result = cbRef(projectReferences2, parent2); - if (result) - return result; + if (result) return result; } return forEach(resolvedProjectReferences2, (resolvedRef, index) => { if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) { return void 0; } const result = cbResolvedRef(resolvedRef, parent2, index); - if (result || !resolvedRef) - return result; + if (result || !resolvedRef) return result; (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef); }); @@ -123693,10 +123773,12 @@ function getLibraryNameFromLibFileName(libFileName) { } return "@typescript/lib-" + path; } +function getLibNameFromLibReference(libReference) { + return toFileNameLowerCase(libReference.fileName); +} function getLibFileNameFromLibReference(libReference) { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); - return { libName, libFileName }; + const libName = getLibNameFromLibReference(libReference); + return libMap.get(libName); } function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { @@ -123716,13 +123798,12 @@ function getReferencedFileLocation(program, ref) { var _a, _b, _c, _d; const file = Debug.checkDefined(program.getSourceFileByPath(ref.file)); const { kind, index } = ref; - let pos, end, packageId, resolutionMode; + let pos, end, packageId; switch (kind) { case 3 /* Import */: const importLiteral = getModuleNameStringLiteralAt(file, index); - packageId = (_b = (_a = program.getResolvedModule(file, importLiteral.text, program.getModeForUsageLocation(file, importLiteral))) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; - if (importLiteral.pos === -1) - return { file, packageId, text: importLiteral.text }; + packageId = (_b = (_a = program.getResolvedModuleFromModuleSpecifier(importLiteral, file)) == null ? void 0 : _a.resolvedModule) == null ? void 0 : _b.packageId; + if (importLiteral.pos === -1) return { file, packageId, text: importLiteral.text }; pos = skipTrivia(file.text, importLiteral.pos); end = importLiteral.end; break; @@ -123730,8 +123811,8 @@ function getReferencedFileLocation(program, ref) { ({ pos, end } = file.referencedFiles[index]); break; case 5 /* TypeReferenceDirective */: - ({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]); - packageId = (_d = (_c = program.getResolvedTypeReferenceDirective(file, toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; + ({ pos, end } = file.typeReferenceDirectives[index]); + packageId = (_d = (_c = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(file.typeReferenceDirectives[index], file)) == null ? void 0 : _c.resolvedTypeReferenceDirective) == null ? void 0 : _d.packageId; break; case 7 /* LibReferenceDirective */: ({ pos, end } = file.libReferenceDirectives[index]); @@ -123742,25 +123823,17 @@ function getReferencedFileLocation(program, ref) { return { file, pos, end, packageId }; } function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { - if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) - return false; - if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) - return false; + if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; + if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) return false; let seenResolvedRefs; - if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) - return false; - if (program.getSourceFiles().some(sourceFileNotUptoDate)) - return false; + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) return false; + if (program.getSourceFiles().some(sourceFileNotUptoDate)) return false; const missingPaths = program.getMissingFilePaths(); - if (missingPaths && forEachEntry(missingPaths, fileExists)) - return false; + if (missingPaths && forEachEntry(missingPaths, fileExists)) return false; const currentOptions = program.getCompilerOptions(); - if (!compareDataObjects(currentOptions, newOptions)) - return false; - if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) - return false; - if (currentOptions.configFile && newOptions.configFile) - return currentOptions.configFile.text === newOptions.configFile.text; + if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) return false; + if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; function sourceFileNotUptoDate(sourceFile) { return !sourceFileVersionUptoDate(sourceFile) || hasInvalidatedResolutions(sourceFile.path); @@ -123773,16 +123846,12 @@ function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, } function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) { if (oldResolvedRef) { - if (contains(seenResolvedRefs, oldResolvedRef)) - return true; + if (contains(seenResolvedRefs, oldResolvedRef)) return true; const refPath2 = resolveProjectReferencePath(oldRef); const newParsedCommandLine = getParsedCommandLine(refPath2); - if (!newParsedCommandLine) - return false; - if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) - return false; - if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) - return false; + if (!newParsedCommandLine) return false; + if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) return false; + if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); return !forEach(oldResolvedRef.references, (childResolvedRef, index) => !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index])); } @@ -123907,8 +123976,7 @@ var plainJSErrors = /* @__PURE__ */ new Set([ Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value.code ]); function shouldProgramCreateNewSourceFiles(program, newOptions) { - if (!program) - return false; + if (!program) return false; return optionsHaveChanges(program.getCompilerOptions(), newOptions, sourceFileAffectingCompilerOptions); } function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion3) { @@ -123926,6 +123994,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion3 } = createProgramOptions; let { oldProgram } = createProgramOptions; + for (const option of commandLineOptionOfCustomType) { + if (hasProperty(options, option.name)) { + if (typeof options[option.name] === "string") { + throw new Error(`${option.name} is a string value; tsconfig JSON must be parsed with parseJsonSourceFileConfigFileContent or getParsedCommandLineOfConfigFile before passing to createProgram`); + } + } + } const reportInvalidIgnoreDeprecations = memoize(() => createOptionValueDiagnostic("ignoreDeprecations", Diagnostics.Invalid_value_for_ignoreDeprecations)); let processingDefaultLibFiles; let processingOtherFiles; @@ -123936,9 +124011,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let classifiableNames; const ambientModuleNameToUnmodifiedFileName = /* @__PURE__ */ new Map(); let fileReasons = createMultiMap(); + let filesWithReferencesProcessed; + let fileReasonsToChain; + let reasonToRelatedInfo; const cachedBindAndCheckDiagnosticsForFile = {}; const cachedDeclarationDiagnosticsForFile = {}; - let resolvedTypeReferenceDirectives = createModeAwareCache(); let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; @@ -123967,6 +124044,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const getDefaultLibraryFileName = memoize(() => host.getDefaultLibFileName(options)); const defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : getDirectoryPath(getDefaultLibraryFileName()); const programDiagnostics = createDiagnosticCollection(); + let lazyProgramDiagnosticExplainingFile = []; const currentDirectory = host.getCurrentDirectory(); const supportedExtensions = getSupportedExtensions(options); const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions); @@ -124084,8 +124162,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } if (rootNames.length) { resolvedProjectReferences == null ? void 0 : resolvedProjectReferences.forEach((parsedRef, index) => { - if (!parsedRef) - return; + if (!parsedRef) return; const out = parsedRef.commandLine.options.outFile; if (useSourceOfProjectReferenceRedirect) { if (out || getEmitModuleKind(parsedRef.commandLine.options) === 0 /* None */) { @@ -124173,6 +124250,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config files = stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = void 0; processingOtherFiles = void 0; + filesWithReferencesProcessed = void 0; } if (oldProgram && host.onReleaseOldSourceFile) { const oldSourceFiles = oldProgram.getSourceFiles(); @@ -124243,7 +124321,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getInstantiationCount: () => getTypeChecker().getInstantiationCount(), getRelationCacheSizes: () => getTypeChecker().getRelationCacheSizes(), getFileProcessingDiagnostics: () => fileProcessingDiagnostics, - getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives, getAutomaticTypeDirectiveNames: () => automaticTypeDirectiveNames, getAutomaticTypeDirectiveResolutions: () => automaticTypeDirectiveResolutions, isSourceFileFromExternalLibrary, @@ -124262,6 +124339,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getResolvedModule, getResolvedModuleFromModuleSpecifier, getResolvedTypeReferenceDirective, + getResolvedTypeReferenceDirectiveFromTypeReferenceDirective, forEachResolvedModule, forEachResolvedTypeReferenceDirective, getCurrentPackagesMap: () => packageMap, @@ -124295,30 +124373,70 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config writeFile: writeFile2 }; onProgramCreateComplete(); - fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { - switch (diagnostic.kind) { - case 1 /* FilePreprocessingFileExplainingDiagnostic */: - return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || emptyArray)); - case 0 /* FilePreprocessingReferencedDiagnostic */: - const { file, pos, end } = getReferencedFileLocation(program, diagnostic.reason); - return programDiagnostics.add(createFileDiagnostic(file, Debug.checkDefined(pos), Debug.checkDefined(end) - pos, diagnostic.diagnostic, ...diagnostic.args || emptyArray)); - case 2 /* ResolutionDiagnostics */: - return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d)); - default: - Debug.assertNever(diagnostic); - } - }); verifyCompilerOptions(); mark("afterProgram"); measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function updateAndGetProgramDiagnostics() { + if (lazyProgramDiagnosticExplainingFile) { + fileProcessingDiagnostics == null ? void 0 : fileProcessingDiagnostics.forEach((diagnostic) => { + switch (diagnostic.kind) { + case 1 /* FilePreprocessingFileExplainingDiagnostic */: + return programDiagnostics.add( + createDiagnosticExplainingFile( + diagnostic.file && getSourceFileByPath(diagnostic.file), + diagnostic.fileProcessingReason, + diagnostic.diagnostic, + diagnostic.args || emptyArray + ) + ); + case 0 /* FilePreprocessingLibReferenceDiagnostic */: + return programDiagnostics.add(filePreprocessingLibreferenceDiagnostic(diagnostic)); + case 2 /* ResolutionDiagnostics */: + return diagnostic.diagnostics.forEach((d) => programDiagnostics.add(d)); + default: + Debug.assertNever(diagnostic); + } + }); + lazyProgramDiagnosticExplainingFile.forEach( + ({ file, diagnostic, args }) => programDiagnostics.add( + createDiagnosticExplainingFile( + file, + /*fileProcessingReason*/ + void 0, + diagnostic, + args + ) + ) + ); + lazyProgramDiagnosticExplainingFile = void 0; + fileReasonsToChain = void 0; + reasonToRelatedInfo = void 0; + } + return programDiagnostics; + } + function filePreprocessingLibreferenceDiagnostic({ reason }) { + const { file, pos, end } = getReferencedFileLocation(program, reason); + const libReference = file.libReferenceDirectives[reason.index]; + const libName = getLibNameFromLibReference(libReference); + const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); + const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); + return createFileDiagnostic( + file, + Debug.checkDefined(pos), + Debug.checkDefined(end) - pos, + suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0, + libName, + suggestion + ); + } function getResolvedModule(file, moduleName, mode) { var _a2; return (_a2 = resolvedModules == null ? void 0 : resolvedModules.get(file.path)) == null ? void 0 : _a2.get(moduleName, mode); } - function getResolvedModuleFromModuleSpecifier(moduleSpecifier) { - const sourceFile = getSourceFileOfNode(moduleSpecifier); + function getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile) { + sourceFile ?? (sourceFile = getSourceFileOfNode(moduleSpecifier)); Debug.assertIsDefined(sourceFile, "`moduleSpecifier` must have a `SourceFile` ancestor. Use `program.getResolvedModule` instead to provide the containing file and resolution mode."); return getResolvedModule(sourceFile, moduleSpecifier.text, getModeForUsageLocation2(sourceFile, moduleSpecifier)); } @@ -124326,6 +124444,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config var _a2; return (_a2 = resolvedTypeReferenceDirectiveNames == null ? void 0 : resolvedTypeReferenceDirectiveNames.get(file.path)) == null ? void 0 : _a2.get(typeDirectiveName, mode); } + function getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeRef, sourceFile) { + return getResolvedTypeReferenceDirective(sourceFile, typeRef.fileName, typeRef.resolutionMode || sourceFile.impliedNodeFormat); + } function forEachResolvedModule(callback, file) { forEachResolution(resolvedModules, callback, file); } @@ -124334,18 +124455,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function forEachResolution(resolutionCache, callback, file) { var _a2; - if (file) - (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); - else - resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); + if (file) (_a2 = resolutionCache == null ? void 0 : resolutionCache.get(file.path)) == null ? void 0 : _a2.forEach((resolution, name, mode) => callback(resolution, name, mode, file.path)); + else resolutionCache == null ? void 0 : resolutionCache.forEach((resolutions, filePath) => resolutions.forEach((resolution, name, mode) => callback(resolution, name, mode, filePath))); } function getPackagesMap() { - if (packageMap) - return packageMap; + if (packageMap) return packageMap; packageMap = /* @__PURE__ */ new Map(); forEachResolvedModule(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + if (resolvedModule == null ? void 0 : resolvedModule.packageId) packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); }); return packageMap; } @@ -124357,29 +124474,24 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function addResolutionDiagnostics(resolution) { var _a2; - if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) - return; + if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) return; (fileProcessingDiagnostics ?? (fileProcessingDiagnostics = [])).push({ kind: 2 /* ResolutionDiagnostics */, diagnostics: resolution.resolutionDiagnostics }); } function addResolutionDiagnosticsFromResolutionOrCache(containingFile, name, resolution, mode) { - if (host.resolveModuleNameLiterals || !host.resolveModuleNames) - return addResolutionDiagnostics(resolution); - if (!moduleResolutionCache || isExternalModuleNameRelative(name)) - return; + if (host.resolveModuleNameLiterals || !host.resolveModuleNames) return addResolutionDiagnostics(resolution); + if (!moduleResolutionCache || isExternalModuleNameRelative(name)) return; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const containingDir = getDirectoryPath(containingFileName); const redirectedReference = getRedirectReferenceForResolution(containingFile); const fromCache = moduleResolutionCache.getFromNonRelativeNameCache(name, mode, containingDir, redirectedReference); - if (fromCache) - addResolutionDiagnostics(fromCache); + if (fromCache) addResolutionDiagnostics(fromCache); } function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) { var _a2, _b2; - if (!moduleNames.length) - return emptyArray; + if (!moduleNames.length) return emptyArray; const containingFileName = getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory); const redirectedReference = getRedirectReferenceForResolution(containingFile); (_a2 = tracing) == null ? void 0 : _a2.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName }); @@ -124392,8 +124504,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile, reusedNames) { var _a2, _b2; - if (!typeDirectiveNames.length) - return []; + if (!typeDirectiveNames.length) return []; const containingSourceFile = !isString(containingFile) ? containingFile : void 0; const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile; const redirectedReference = containingSourceFile && getRedirectReferenceForResolution(containingSourceFile); @@ -124407,26 +124518,20 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getRedirectReferenceForResolution(file) { const redirect = getResolvedProjectReferenceToRedirect(file.originalFileName); - if (redirect || !isDeclarationFileName(file.originalFileName)) - return redirect; + if (redirect || !isDeclarationFileName(file.originalFileName)) return redirect; const resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.path); - if (resultFromDts) - return resultFromDts; - if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) - return void 0; + if (resultFromDts) return resultFromDts; + if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return void 0; const realDeclarationPath = toPath3(host.realpath(file.originalFileName)); return realDeclarationPath === file.path ? void 0 : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath); } function getRedirectReferenceForResolutionFromSourceOfProject(filePath) { const source = getSourceOfProjectReferenceRedirect(filePath); - if (isString(source)) - return getResolvedProjectReferenceToRedirect(source); - if (!source) - return void 0; + if (isString(source)) return getResolvedProjectReferenceToRedirect(source); + if (!source) return void 0; return forEachResolvedProjectReference2((resolvedRef) => { const out = resolvedRef.commandLine.options.outFile; - if (!out) - return void 0; + if (!out) return void 0; return toPath3(out) === filePath ? resolvedRef : void 0; }); } @@ -124441,12 +124546,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config false )) { const basename = getBaseFileName(a.fileName); - if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") - return 0; + if (basename === "lib.d.ts" || basename === "lib.es6.d.ts") return 0; const name = removeSuffix(removePrefix(basename, "lib."), ".d.ts"); const index = libs.indexOf(name); - if (index !== -1) - return index + 1; + if (index !== -1) return index + 1; } return libs.length + 2; } @@ -124597,8 +124700,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } (unknownTypeReferenceDirectiveNames ?? (unknownTypeReferenceDirectiveNames = [])).push(entry); } - if (!unknownTypeReferenceDirectiveNames) - return result || emptyArray; + if (!unknownTypeReferenceDirectiveNames) return result || emptyArray; const resolutions = resolveTypeReferenceDirectiveNamesWorker( unknownTypeReferenceDirectiveNames, containingFile, @@ -124764,8 +124866,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (name) => oldProgram.getResolvedModule(newSourceFile, name.text, getModeForUsageLocation2(newSourceFile, name)), moduleResolutionIsEqualTo ); - if (resolutionsChanged) - structureIsReused = 1 /* SafeModules */; + if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; const typesReferenceDirectives = newSourceFile.typeReferenceDirectives; const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesReusingOldState(typesReferenceDirectives, newSourceFile); (resolvedTypeReferenceDirectiveNamesProcessing ?? (resolvedTypeReferenceDirectiveNamesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, typeReferenceResolutions); @@ -124775,8 +124876,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (name) => oldProgram.getResolvedTypeReferenceDirective(newSourceFile, getTypeReferenceResolutionName(name), getModeForFileReference(name, newSourceFile.impliedNodeFormat)), typeDirectiveIsEqualTo ); - if (typeReferenceResolutionsChanged) - structureIsReused = 1 /* SafeModules */; + if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; } if (structureIsReused !== 2 /* Completely */) { return structureIsReused; @@ -124788,12 +124888,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return 1 /* SafeModules */; } if (host.hasChangedAutomaticTypeDirectiveNames) { - if (host.hasChangedAutomaticTypeDirectiveNames()) - return 1 /* SafeModules */; + if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; } else { automaticTypeDirectiveNames = getAutomaticTypeDirectiveNames(options, host); - if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames)) - return 1 /* SafeModules */; + if (!arrayIsEqualTo(oldProgram.getAutomaticTypeDirectiveNames(), automaticTypeDirectiveNames)) return 1 /* SafeModules */; } missingFileNames = oldProgram.getMissingFilePaths(); Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length); @@ -124817,7 +124915,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config files = newSourceFiles; fileReasons = oldProgram.getFileIncludeReasons(); fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); automaticTypeDirectiveNames = oldProgram.getAutomaticTypeDirectiveNames(); automaticTypeDirectiveResolutions = oldProgram.getAutomaticTypeDirectiveResolutions(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; @@ -124852,10 +124949,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config readFile: (f) => host.readFile(f), fileExists: (f) => { const path = toPath3(f); - if (getSourceFileByPath(path)) - return true; - if (missingFileNames.has(path)) - return false; + if (getSourceFileByPath(path)) return true; + if (missingFileNames.has(path)) return false; return host.fileExists(f); }, realpath: maybeBind(host, host.realpath), @@ -124951,20 +125046,27 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function emitWorker(program2, sourceFile, writeFileCallback, cancellationToken, emitOnly, customTransformers, forceDtsEmit) { if (!forceDtsEmit) { const result = handleNoEmitOptions(program2, sourceFile, writeFileCallback, cancellationToken); - if (result) - return result; + if (result) return result; } - const emitResolver = getTypeChecker().getEmitResolver(options.outFile ? void 0 : sourceFile, cancellationToken); + const typeChecker2 = getTypeChecker(); + const emitResolver = typeChecker2.getEmitResolver( + options.outFile ? void 0 : sourceFile, + cancellationToken, + emitResolverSkipsTypeChecking(emitOnly, forceDtsEmit) + ); mark("beforeEmit"); - const emitResult = emitFiles( - emitResolver, - getEmitHost(writeFileCallback), - sourceFile, - getTransformers(options, customTransformers, emitOnly), - emitOnly, - /*onlyBuildInfo*/ - false, - forceDtsEmit + const emitResult = typeChecker2.runWithCancellationToken( + cancellationToken, + () => emitFiles( + emitResolver, + getEmitHost(writeFileCallback), + sourceFile, + getTransformers(options, customTransformers, emitOnly), + emitOnly, + /*onlyBuildInfo*/ + false, + forceDtsEmit + ) ); mark("afterEmit"); measure("Emit", "beforeEmit", "afterEmit"); @@ -125005,7 +125107,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (skipTypeChecking(sourceFile, options, program)) { return emptyArray; } - const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + const programDiagnosticsInFile = updateAndGetProgramDiagnostics().getDiagnostics(sourceFile.fileName); if (!((_a2 = sourceFile.commentDirectives) == null ? void 0 : _a2.length)) { return programDiagnosticsInFile; } @@ -125057,15 +125159,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const isJs = sourceFile.scriptKind === 1 /* JS */ || sourceFile.scriptKind === 2 /* JSX */; const isCheckJs = isJs && isCheckJsEnabledForFile(sourceFile, options); const isPlainJs = isPlainJsFile(sourceFile, options.checkJs); - const isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false; - const includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ || sourceFile.scriptKind === 5 /* External */ || isPlainJs || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */); - let bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : emptyArray; - let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker2.getDiagnostics(sourceFile, cancellationToken) : emptyArray; + let bindDiagnostics = sourceFile.bindDiagnostics; + let checkDiagnostics = typeChecker2.getDiagnostics(sourceFile, cancellationToken); if (isPlainJs) { bindDiagnostics = filter(bindDiagnostics, (d) => plainJSErrors.has(d.code)); checkDiagnostics = filter(checkDiagnostics, (d) => plainJSErrors.has(d.code)); } - return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics && !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0); + return getMergedBindAndCheckDiagnostics(sourceFile, !isPlainJs, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : void 0); }); } function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, ...allDiagnostics) { @@ -125352,16 +125452,15 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getOptionsDiagnostics() { return sortAndDeduplicateDiagnostics(concatenate( - programDiagnostics.getGlobalDiagnostics(), + updateAndGetProgramDiagnostics().getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile() )); } function getOptionsDiagnosticsOfConfigFile() { - if (!options.configFile) - return emptyArray; - let diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName); + if (!options.configFile) return emptyArray; + let diagnostics = updateAndGetProgramDiagnostics().getDiagnostics(options.configFile.fileName); forEachResolvedProjectReference2((resolvedRef) => { - diagnostics = concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName)); + diagnostics = concatenate(diagnostics, updateAndGetProgramDiagnostics().getDiagnostics(resolvedRef.sourceFile.fileName)); }); return diagnostics; } @@ -125394,9 +125493,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config void 0, /*importClause*/ void 0, - externalHelpersModuleReference, - /*attributes*/ - void 0 + externalHelpersModuleReference ); addInternalEmitFlags(importDecl, 2 /* NeverApplyImportHelper */); setParent(externalHelpersModuleReference, importDecl); @@ -125414,7 +125511,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let imports; let moduleAugmentations; let ambientModules; - if ((getIsolatedModules(options) || isExternalModuleFile) && !file.isDeclarationFile) { + if (isJavaScriptFile || !file.isDeclarationFile && (getIsolatedModules(options) || isExternalModule(file))) { if (options.importHelpers) { imports = [createSyntheticImport(externalHelpersModuleNameText, file)]; } @@ -125535,7 +125632,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function getLibFileFromReference(ref) { var _a2; - const { libFileName } = getLibFileNameFromLibReference(ref); + const libFileName = getLibFileNameFromLibReference(ref); const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } @@ -125571,15 +125668,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return sourceFile; } else { const sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile2(fileName); - if (sourceFileNoExtension) - return sourceFileNoExtension; + if (sourceFileNoExtension) return sourceFileNoExtension; if (fail && options.allowNonTsExtensions) { fail(Diagnostics.File_0_not_found, fileName); return void 0; } const sourceFileWithAddedExtension = forEach(supportedExtensions[0], (extension) => getSourceFile2(fileName + extension)); - if (fail && !sourceFileWithAddedExtension) - fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); + if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'"); return sourceFileWithAddedExtension; } } @@ -125654,27 +125749,30 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let source = getSourceOfProjectReferenceRedirect(path); if (!source && host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && fileName.includes(nodeModulesPathPart)) { const realPath2 = toPath3(host.realpath(fileName)); - if (realPath2 !== path) - source = getSourceOfProjectReferenceRedirect(realPath2); + if (realPath2 !== path) source = getSourceOfProjectReferenceRedirect(realPath2); } if (source) { const file2 = isString(source) ? findSourceFile(source, isDefaultLib, ignoreNoDefaultLib, reason, packageId) : void 0; - if (file2) - addFileToFilesByName( - file2, - path, - fileName, - /*redirectedPath*/ - void 0 - ); + if (file2) addFileToFilesByName( + file2, + path, + fileName, + /*redirectedPath*/ + void 0 + ); return file2; } } const originalFileName = fileName; if (filesByName.has(path)) { const file2 = filesByName.get(path); - addFileIncludeReason(file2 || void 0, reason); - if (file2 && !(options.forceConsistentCasingInFileNames === false)) { + const addedReason = addFileIncludeReason( + file2 || void 0, + reason, + /*checkExisting*/ + true + ); + if (file2 && addedReason && !(options.forceConsistentCasingInFileNames === false)) { const checkedName = file2.fileName; const isRedirect = toPath3(checkedName) !== toPath3(fileName); if (isRedirect) { @@ -125706,7 +125804,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return file2 || void 0; } let redirectedPath; - if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) { + if (!useSourceOfProjectReferenceRedirect) { const redirectProject = getProjectReferenceRedirectProject(fileName); if (redirectProject) { if (redirectProject.commandLine.options.outFile) { @@ -125737,7 +125835,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const dupFile = createRedirectedSourceFile(fileFromPackageId, file, fileName, path, toPath3(fileName), originalFileName, sourceFileOptions); redirectTargetsMap.add(fileFromPackageId.path, fileName); addFileToFilesByName(dupFile, path, fileName, redirectedPath); - addFileIncludeReason(dupFile, reason); + addFileIncludeReason( + dupFile, + reason, + /*checkExisting*/ + false + ); sourceFileToPackageName.set(path, packageIdToPackageName(packageId)); processingOtherFiles.push(dupFile); return dupFile; @@ -125755,7 +125858,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config file.originalFileName = originalFileName; file.packageJsonLocations = ((_a2 = sourceFileOptions.packageJsonLocations) == null ? void 0 : _a2.length) ? sourceFileOptions.packageJsonLocations : void 0; file.packageJsonScope = sourceFileOptions.packageJsonScope; - addFileIncludeReason(file, reason); + addFileIncludeReason( + file, + reason, + /*checkExisting*/ + false + ); if (host.useCaseSensitiveFileNames()) { const pathLowerCase = toFileNameLowerCase(path); const existingFile = filesByNameIgnoreCase.get(pathLowerCase); @@ -125779,12 +125887,16 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } else { processingOtherFiles.push(file); } + (filesWithReferencesProcessed ?? (filesWithReferencesProcessed = /* @__PURE__ */ new Set())).add(file.path); } return file; } - function addFileIncludeReason(file, reason) { - if (file) + function addFileIncludeReason(file, reason, checkExisting) { + if (file && (!checkExisting || !isReferencedFile(reason) || !(filesWithReferencesProcessed == null ? void 0 : filesWithReferencesProcessed.has(reason.file)))) { fileReasons.add(file.path, reason); + return true; + } + return false; } function addFileToFilesByName(file, path, fileName, redirectedPath) { if (redirectedPath) { @@ -125796,10 +125908,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function updateFilesByNameMap(fileName, path, file) { filesByName.set(path, file); - if (file !== void 0) - missingFileNames.delete(path); - else - missingFileNames.set(path, fileName); + if (file !== void 0) missingFileNames.delete(path); + else missingFileNames.set(path, fileName); } function getProjectReferenceRedirect(fileName) { const referencedProject = getProjectReferenceRedirectProject(fileName); @@ -125831,8 +125941,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return forEachResolvedProjectReference(resolvedProjectReferences, cb); } function getSourceOfProjectReferenceRedirect(path) { - if (!isDeclarationFileName(path)) - return void 0; + if (!isDeclarationFileName(path)) return void 0; if (mapFromToProjectReferenceRedirectSource === void 0) { mapFromToProjectReferenceRedirectSource = /* @__PURE__ */ new Map(); forEachResolvedProjectReference2((resolvedRef) => { @@ -125877,15 +125986,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function processTypeReferenceDirectives(file) { const typeDirectives = file.typeReferenceDirectives; - if (!typeDirectives.length) - return; + if (!typeDirectives.length) return; const resolutions = (resolvedTypeReferenceDirectiveNamesProcessing == null ? void 0 : resolvedTypeReferenceDirectiveNamesProcessing.get(file.path)) || resolveTypeReferenceDirectiveNamesReusingOldState(typeDirectives, file); const resolutionsInFile = createModeAwareCache(); (resolvedTypeReferenceDirectiveNames ?? (resolvedTypeReferenceDirectiveNames = /* @__PURE__ */ new Map())).set(file.path, resolutionsInFile); for (let index = 0; index < typeDirectives.length; index++) { const ref = file.typeReferenceDirectives[index]; const resolvedTypeReferenceDirective = resolutions[index]; - const fileName = toFileNameLowerCase(ref.fileName); + const fileName = ref.fileName; resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); const mode = ref.resolutionMode || getDefaultResolutionModeForFile2(file); processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); @@ -125902,56 +126010,20 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config (_b2 = tracing) == null ? void 0 : _b2.pop(); } function processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolution, reason) { - var _a2; addResolutionDiagnostics(resolution); - const previousResolution = (_a2 = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode)) == null ? void 0 : _a2.resolvedTypeReferenceDirective; - if (previousResolution && previousResolution.primary) { - return; - } - let saveResolution = true; const { resolvedTypeReferenceDirective } = resolution; if (resolvedTypeReferenceDirective) { - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth++; - if (resolvedTypeReferenceDirective.primary) { - processSourceFile( - resolvedTypeReferenceDirective.resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - resolvedTypeReferenceDirective.packageId, - reason - ); - } else { - if (previousResolution) { - if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) { - const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName); - const existingFile = getSourceFile(previousResolution.resolvedFileName); - if (otherFileText !== existingFile.text) { - addFilePreprocessingFileExplainingDiagnostic( - existingFile, - reason, - Diagnostics.Conflicting_definitions_for_0_found_at_1_and_2_Consider_installing_a_specific_version_of_this_library_to_resolve_the_conflict, - [typeReferenceDirective, resolvedTypeReferenceDirective.resolvedFileName, previousResolution.resolvedFileName] - ); - } - } - saveResolution = false; - } else { - processSourceFile( - resolvedTypeReferenceDirective.resolvedFileName, - /*isDefaultLib*/ - false, - /*ignoreNoDefaultLib*/ - false, - resolvedTypeReferenceDirective.packageId, - reason - ); - } - } - if (resolvedTypeReferenceDirective.isExternalLibraryImport) - currentNodeModulesDepth--; + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth++; + processSourceFile( + resolvedTypeReferenceDirective.resolvedFileName, + /*isDefaultLib*/ + false, + /*ignoreNoDefaultLib*/ + false, + resolvedTypeReferenceDirective.packageId, + reason + ); + if (resolvedTypeReferenceDirective.isExternalLibraryImport) currentNodeModulesDepth--; } else { addFilePreprocessingFileExplainingDiagnostic( /*file*/ @@ -125961,14 +126033,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config [typeReferenceDirective] ); } - if (saveResolution) { - resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolution); - } } function pathForLibFile(libFileName) { const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); - if (existing) - return existing.actual; + if (existing) return existing.actual; const result = pathForLibFileWorker(libFileName); (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); return result.actual; @@ -125976,8 +126044,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function pathForLibFileWorker(libFileName) { var _a2, _b2, _c2, _d2, _e2; const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); - if (existing) - return existing; + if (existing) return existing; if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); if (oldResolution) { @@ -126014,7 +126081,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const { libName, libFileName } = getLibFileNameFromLibReference(libReference); + const libFileName = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -126025,15 +126092,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config { kind: 7 /* LibReferenceDirective */, file: file.path, index } ); } else { - const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts"); - const suggestion = getSpellingSuggestion(unqualifiedLibName, libs, identity); - const diagnostic = suggestion ? Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : Diagnostics.Cannot_find_lib_definition_for_0; - const args = suggestion ? [libName, suggestion] : [libName]; (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({ - kind: 0 /* FilePreprocessingReferencedDiagnostic */, - reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index }, - diagnostic, - args + kind: 0 /* FilePreprocessingLibReferenceDiagnostic */, + reason: { kind: 7 /* LibReferenceDirective */, file: file.path, index } }); } }); @@ -126060,7 +126121,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config continue; } const isFromNodeModulesSearch = resolution.isExternalLibraryImport; - const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension); + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension) && !getProjectReferenceRedirectProject(resolution.resolvedFileName); const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile && (!resolution.originalPath || pathContainsNodeModules(resolution.resolvedFileName)); const resolvedFileName = resolution.resolvedFileName; if (isFromNodeModulesSearch) { @@ -126094,7 +126155,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!sourceFile.isDeclarationFile) { const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { - addProgramDiagnosticExplainingFile( + addLazyProgramDiagnosticExplainingFile( sourceFile, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory] @@ -126224,7 +126285,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const rootPaths = new Set(rootNames.map(toPath3)); for (const file of files) { if (sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) { - addProgramDiagnosticExplainingFile( + addLazyProgramDiagnosticExplainingFile( file, Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, [file.fileName, options.configFilePath || ""] @@ -126355,6 +126416,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit"); } } + if (options.noCheck) { + if (options.noEmit) { + createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noCheck", "noEmit"); + } + } if (options.emitDecoratorMetadata && !options.experimentalDecorators) { createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"); } @@ -126579,31 +126645,85 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config }); } function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) { - var _a2; + let seenReasons; + const reasons = file && fileReasons.get(file.path); let fileIncludeReasons; let relatedInfo; let locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : void 0; - if (file) - (_a2 = fileReasons.get(file.path)) == null ? void 0 : _a2.forEach(processReason); - if (fileProcessingReason) - processReason(fileProcessingReason); - if (locationReason && (fileIncludeReasons == null ? void 0 : fileIncludeReasons.length) === 1) - fileIncludeReasons = void 0; + let fileIncludeReasonDetails; + let redirectInfo; + let cachedChain = file && (fileReasonsToChain == null ? void 0 : fileReasonsToChain.get(file.path)); + let chain; + if (cachedChain) { + if (cachedChain.fileIncludeReasonDetails) { + seenReasons = new Set(reasons); + reasons == null ? void 0 : reasons.forEach(populateRelatedInfo); + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + } + redirectInfo = cachedChain.redirectInfo; + } else { + reasons == null ? void 0 : reasons.forEach(processReason); + redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, getCompilerOptionsForFile(file)); + } + if (fileProcessingReason) processReason(fileProcessingReason); + const processedExtraReason = (seenReasons == null ? void 0 : seenReasons.size) !== (reasons == null ? void 0 : reasons.length); + if (locationReason && (seenReasons == null ? void 0 : seenReasons.size) === 1) seenReasons = void 0; + if (seenReasons && cachedChain) { + if (cachedChain.details && !processedExtraReason) { + chain = chainDiagnosticMessages(cachedChain.details, diagnostic, ...args || emptyArray); + } else if (cachedChain.fileIncludeReasonDetails) { + if (!processedExtraReason) { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasonDetails = cachedChain.fileIncludeReasonDetails; + } else { + fileIncludeReasons = cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length); + } + } else { + if (!cachedFileIncludeDetailsHasProcessedExtraReason()) { + fileIncludeReasons = [...cachedChain.fileIncludeReasonDetails.next, fileIncludeReasons[0]]; + } else { + fileIncludeReasons = append(cachedChain.fileIncludeReasonDetails.next.slice(0, reasons.length), fileIncludeReasons[0]); + } + } + } + } + if (!chain) { + if (!fileIncludeReasonDetails) fileIncludeReasonDetails = seenReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); + chain = chainDiagnosticMessages( + redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, + diagnostic, + ...args || emptyArray + ); + } + if (file) { + if (cachedChain) { + if (!cachedChain.fileIncludeReasonDetails || !processedExtraReason && fileIncludeReasonDetails) { + cachedChain.fileIncludeReasonDetails = fileIncludeReasonDetails; + } + } else { + (fileReasonsToChain ?? (fileReasonsToChain = /* @__PURE__ */ new Map())).set(file.path, cachedChain = { fileIncludeReasonDetails, redirectInfo }); + } + if (!cachedChain.details && !processedExtraReason) cachedChain.details = chain.next; + } const location = locationReason && getReferencedFileLocation(program, locationReason); - const fileIncludeReasonDetails = fileIncludeReasons && chainDiagnosticMessages(fileIncludeReasons, Diagnostics.The_file_is_in_the_program_because_Colon); - const optionsForFile = file && getCompilerOptionsForFile(file) || options; - const redirectInfo = file && explainIfFileIsRedirectAndImpliedFormat(file, optionsForFile); - const chain = chainDiagnosticMessages(redirectInfo ? fileIncludeReasonDetails ? [fileIncludeReasonDetails, ...redirectInfo] : redirectInfo : fileIncludeReasonDetails, diagnostic, ...args || emptyArray); return location && isReferenceFileLocation(location) ? createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) : createCompilerDiagnosticFromMessageChain(chain, relatedInfo); function processReason(reason) { - (fileIncludeReasons || (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason)); + if (seenReasons == null ? void 0 : seenReasons.has(reason)) return; + (seenReasons ?? (seenReasons = /* @__PURE__ */ new Set())).add(reason); + (fileIncludeReasons ?? (fileIncludeReasons = [])).push(fileIncludeReasonToDiagnostics(program, reason)); + populateRelatedInfo(reason); + } + function populateRelatedInfo(reason) { if (!locationReason && isReferencedFile(reason)) { locationReason = reason; } else if (locationReason !== reason) { - relatedInfo = append(relatedInfo, fileIncludeReasonToRelatedInformation(reason)); + relatedInfo = append(relatedInfo, getFileIncludeReasonToRelatedInformation(reason)); } - if (reason === fileProcessingReason) - fileProcessingReason = void 0; + } + function cachedFileIncludeDetailsHasProcessedExtraReason() { + var _a2; + return ((_a2 = cachedChain.fileIncludeReasonDetails.next) == null ? void 0 : _a2.length) !== (reasons == null ? void 0 : reasons.length); } } function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) { @@ -126615,14 +126735,13 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config args }); } - function addProgramDiagnosticExplainingFile(file, diagnostic, args) { - programDiagnostics.add(createDiagnosticExplainingFile( - file, - /*fileProcessingReason*/ - void 0, - diagnostic, - args - )); + function addLazyProgramDiagnosticExplainingFile(file, diagnostic, args) { + lazyProgramDiagnosticExplainingFile.push({ file, diagnostic, args }); + } + function getFileIncludeReasonToRelatedInformation(reason) { + let relatedInfo = reasonToRelatedInfo == null ? void 0 : reasonToRelatedInfo.get(reason); + if (relatedInfo === void 0) (reasonToRelatedInfo ?? (reasonToRelatedInfo = /* @__PURE__ */ new Map())).set(reason, relatedInfo = fileIncludeReasonToRelatedInformation(reason) ?? false); + return relatedInfo || void 0; } function fileIncludeReasonToRelatedInformation(reason) { if (isReferencedFile(reason)) { @@ -126651,14 +126770,12 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config message2 ) : void 0; } - if (!options.configFile) - return void 0; + if (!options.configFile) return void 0; let configFileNode; let message; switch (reason.kind) { case 0 /* RootFile */: - if (!options.configFile.configFileSpecs) - return void 0; + if (!options.configFile.configFileSpecs) return void 0; const fileName = getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory); const matchedByFiles = getMatchedFileSpec(program, fileName); if (matchedByFiles) { @@ -126667,8 +126784,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config break; } const matchedByInclude = getMatchedIncludeSpec(program, fileName); - if (!matchedByInclude || !isString(matchedByInclude)) - return void 0; + if (!matchedByInclude || !isString(matchedByInclude)) return void 0; configFileNode = getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude); message = Diagnostics.File_is_matched_by_include_pattern_specified_here; break; @@ -126676,8 +126792,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 2 /* OutputFromProjectReference */: const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]); const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0); - if (!referenceInfo) - return void 0; + if (!referenceInfo) return void 0; const { sourceFile, index } = referenceInfo; const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); return referencesSyntax && referencesSyntax.elements.length > index ? createDiagnosticForNodeInSourceFile( @@ -126686,8 +126801,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config reason.kind === 2 /* OutputFromProjectReference */ ? Diagnostics.File_is_output_from_referenced_project_specified_here : Diagnostics.File_is_source_from_referenced_project_specified_here ) : void 0; case 8 /* AutomaticTypeDirectiveFile */: - if (!options.types) - return void 0; + if (!options.types) return void 0; configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference); message = Diagnostics.File_is_entry_point_of_type_library_specified_here; break; @@ -126724,10 +126838,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!options2.composite || options2.noEmit) { const inputs = parent2 ? parent2.commandLine.fileNames : rootNames; if (inputs.length) { - if (!options2.composite) - createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - if (options2.noEmit) - createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); + if (!options2.composite) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + if (options2.noEmit) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); } } if (!parent2 && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) { @@ -126964,8 +127076,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { const originalDirectoryExists = host.compilerHost.directoryExists; const originalGetDirectories = host.compilerHost.getDirectories; const originalRealpath = host.compilerHost.realpath; - if (!host.useSourceOfProjectReferenceRedirect) - return { onProgramCreateComplete: noop, fileExists }; + if (!host.useSourceOfProjectReferenceRedirect) return { onProgramCreateComplete: noop, fileExists }; host.compilerHost.fileExists = fileExists; let directoryExists; if (originalDirectoryExists) { @@ -126974,8 +127085,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { handleDirectoryCouldBeSymlink(path); return true; } - if (!host.getResolvedProjectReferences()) - return false; + if (!host.getResolvedProjectReferences()) return false; if (!setOfDeclarationDirectories) { setOfDeclarationDirectories = /* @__PURE__ */ new Set(); host.forEachResolvedProjectReference((ref) => { @@ -127013,12 +127123,9 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { host.compilerHost.getDirectories = originalGetDirectories; } function fileExists(file) { - if (originalFileExists.call(host.compilerHost, file)) - return true; - if (!host.getResolvedProjectReferences()) - return false; - if (!isDeclarationFileName(file)) - return false; + if (originalFileExists.call(host.compilerHost, file)) return true; + if (!host.getResolvedProjectReferences()) return false; + if (!isDeclarationFileName(file)) return false; return fileOrDirectoryExistsUsingSource( file, /*isFile*/ @@ -127041,14 +127148,11 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { } function handleDirectoryCouldBeSymlink(directory) { var _a; - if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) - return; - if (!originalRealpath || !directory.includes(nodeModulesPathPart)) - return; + if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; + if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return; const symlinkCache = host.getSymlinkCache(); const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); - if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) - return; + if ((_a = symlinkCache.getSymlinkedDirectories()) == null ? void 0 : _a.has(directoryPath)) return; const real = normalizePath(originalRealpath.call(host.compilerHost, directory)); let realPath2; if (real === directory || (realPath2 = ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) { @@ -127064,22 +127168,17 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host) { var _a; const fileOrDirectoryExistsUsingSource2 = isFile ? (file) => fileExistsIfProjectReferenceDts(file) : (dir) => directoryExistsIfProjectReferenceDeclDir(dir); const result = fileOrDirectoryExistsUsingSource2(fileOrDirectory); - if (result !== void 0) - return result; + if (result !== void 0) return result; const symlinkCache = host.getSymlinkCache(); const symlinkedDirectories = symlinkCache.getSymlinkedDirectories(); - if (!symlinkedDirectories) - return false; + if (!symlinkedDirectories) return false; const fileOrDirectoryPath = host.toPath(fileOrDirectory); - if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) - return false; - if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) - return true; + if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false; + if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) == null ? void 0 : _a.has(fileOrDirectoryPath))) return true; return firstDefinedIterator( symlinkedDirectories.entries(), ([directoryPath, symlinkedDirectory]) => { - if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) - return void 0; + if (!symlinkedDirectory || !startsWith(fileOrDirectoryPath, directoryPath)) return void 0; const result2 = fileOrDirectoryExistsUsingSource2(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath)); if (isFile && result2) { const absolutePath = getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory()); @@ -127100,8 +127199,7 @@ function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) program.getSemanticDiagnostics(sourceFile, cancellationToken); return sourceFile || options.outFile ? emitSkippedWithNoDiagnostics : program.emitBuildInfo(writeFile2, cancellationToken); } - if (!options.noEmitOnError) - return void 0; + if (!options.noEmitOnError) return void 0; let diagnostics = [ ...program.getOptionsDiagnostics(cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), @@ -127115,13 +127213,11 @@ function handleNoEmitOptions(program, sourceFile, writeFile2, cancellationToken) cancellationToken ); } - if (!diagnostics.length) - return void 0; + if (!diagnostics.length) return void 0; let emittedFiles; if (!sourceFile && !options.outFile) { const emitResult = program.emitBuildInfo(writeFile2, cancellationToken); - if (emitResult.diagnostics) - diagnostics = [...diagnostics, ...emitResult.diagnostics]; + if (emitResult.diagnostics) diagnostics = [...diagnostics, ...emitResult.diagnostics]; emittedFiles = emitResult.emittedFiles; } return { diagnostics, sourceMaps: void 0, emittedFiles, emitSkipped: true }; @@ -127194,13 +127290,11 @@ function getModuleNames({ imports, moduleAugmentations }) { return res; } function getModuleNameStringLiteralAt({ imports, moduleAugmentations }, index) { - if (index < imports.length) - return imports[index]; + if (index < imports.length) return imports[index]; let augIndex = imports.length; for (const aug of moduleAugmentations) { if (aug.kind === 11 /* StringLiteral */) { - if (index === augIndex) - return aug; + if (index === augIndex) return aug; augIndex++; } } @@ -127230,6 +127324,7 @@ var BuilderState; getKeys: (v) => reverse.get(v), getValues: (k) => forward.get(k), keys: () => forward.keys(), + size: () => forward.size, deleteKey: (k) => { (deleted || (deleted = /* @__PURE__ */ new Set())).add(k); const set = forward.get(k); @@ -127325,11 +127420,9 @@ var BuilderState; if (sourceFile.moduleAugmentations.length) { const checker = program.getTypeChecker(); for (const moduleName of sourceFile.moduleAugmentations) { - if (!isStringLiteral(moduleName)) - continue; + if (!isStringLiteral(moduleName)) continue; const symbol = checker.getSymbolAtLocation(moduleName); - if (!symbol) - continue; + if (!symbol) continue; addReferenceFromAmbientModule(symbol); } } @@ -127358,12 +127451,15 @@ var BuilderState; return oldState && !oldState.referencedMap === !newReferencedMap; } BuilderState2.canReuseOldState = canReuseOldState; + function createReferencedMap(options) { + return options.module !== 0 /* None */ && !options.outFile ? createManyToManyPathMap() : void 0; + } + BuilderState2.createReferencedMap = createReferencedMap; function create(newProgram, oldState, disableUseFileVersionAsSignature) { var _a, _b; const fileInfos = /* @__PURE__ */ new Map(); const options = newProgram.getCompilerOptions(); - const isOutFile = options.outFile; - const referencedMap = options.module !== 0 /* None */ && !isOutFile ? createManyToManyPathMap() : void 0; + const referencedMap = createReferencedMap(options); const useOldState = canReuseOldState(referencedMap, oldState); newProgram.getTypeChecker(); for (const sourceFile of newProgram.getSourceFiles()) { @@ -127380,7 +127476,7 @@ var BuilderState; version: version2, signature, // No need to calculate affectsGlobalScope with --out since its not used at all - affectsGlobalScope: !isOutFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0, + affectsGlobalScope: !options.outFile ? isFileAffectingGlobalScope(sourceFile) || void 0 : void 0, impliedFormat: sourceFile.impliedNodeFormat }); } @@ -127453,22 +127549,19 @@ var BuilderState; BuilderState2.computeDtsSignature = computeDtsSignature; function updateShapeSignature(state, programOfThisState, sourceFile, cancellationToken, host, useFileVersionAsSignature = state.useFileVersionAsSignature) { var _a; - if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) - return false; + if ((_a = state.hasCalledUpdateShapeSignature) == null ? void 0 : _a.has(sourceFile.resolvedPath)) return false; const info = state.fileInfos.get(sourceFile.resolvedPath); const prevSignature = info.signature; let latestSignature; if (!sourceFile.isDeclarationFile && !useFileVersionAsSignature) { computeDtsSignature(programOfThisState, sourceFile, cancellationToken, host, (signature) => { latestSignature = signature; - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 0 /* ComputedDts */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 0 /* ComputedDts */); }); } if (latestSignature === void 0) { latestSignature = sourceFile.version; - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 2 /* UsedVersion */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, 2 /* UsedVersion */); } (state.oldSignatures || (state.oldSignatures = /* @__PURE__ */ new Map())).set(sourceFile.resolvedPath, prevSignature || false); (state.hasCalledUpdateShapeSignature || (state.hasCalledUpdateShapeSignature = /* @__PURE__ */ new Set())).add(sourceFile.resolvedPath); @@ -127535,8 +127628,7 @@ var BuilderState; return state.allFilesExcludingDefaultLibraryFile; } let result; - if (firstSourceFile) - addSourceFile(firstSourceFile); + if (firstSourceFile) addSourceFile(firstSourceFile); for (const sourceFile of programOfThisState.getSourceFiles()) { if (sourceFile !== firstSourceFile) { addSourceFile(sourceFile); @@ -127598,31 +127690,22 @@ var BuilderFileEmit = /* @__PURE__ */ ((BuilderFileEmit2) => { })(BuilderFileEmit || {}); function getBuilderFileEmit(options) { let result = 1 /* Js */; - if (options.sourceMap) - result = result | 2 /* JsMap */; - if (options.inlineSourceMap) - result = result | 4 /* JsInlineMap */; - if (getEmitDeclarations(options)) - result = result | 8 /* Dts */; - if (options.declarationMap) - result = result | 16 /* DtsMap */; - if (options.emitDeclarationOnly) - result = result & 24 /* AllDts */; + if (options.sourceMap) result = result | 2 /* JsMap */; + if (options.inlineSourceMap) result = result | 4 /* JsInlineMap */; + if (getEmitDeclarations(options)) result = result | 8 /* Dts */; + if (options.declarationMap) result = result | 16 /* DtsMap */; + if (options.emitDeclarationOnly) result = result & 24 /* AllDts */; return result; } function getPendingEmitKind(optionsOrEmitKind, oldOptionsOrEmitKind) { const oldEmitKind = oldOptionsOrEmitKind && (isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind)); const emitKind = isNumber(optionsOrEmitKind) ? optionsOrEmitKind : getBuilderFileEmit(optionsOrEmitKind); - if (oldEmitKind === emitKind) - return 0 /* None */; - if (!oldEmitKind || !emitKind) - return emitKind; + if (oldEmitKind === emitKind) return 0 /* None */; + if (!oldEmitKind || !emitKind) return emitKind; const diff = oldEmitKind ^ emitKind; let result = 0 /* None */; - if (diff & 7 /* AllJs */) - result = emitKind & 7 /* AllJs */; - if (diff & 24 /* AllDts */) - result = result | emitKind & 24 /* AllDts */; + if (diff & 7 /* AllJs */) result = emitKind & 7 /* AllJs */; + if (diff & 24 /* AllDts */) result = result | emitKind & 24 /* AllDts */; return result; } function hasSameKeys(map1, map2) { @@ -127682,19 +127765,17 @@ function createBuilderProgramState(newProgram, oldState) { if (emitDiagnostics) { (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set( sourceFilePath, - oldState.hasReusableDiagnostic ? convertToDiagnostics(emitDiagnostics, newProgram) : repopulateDiagnostics(emitDiagnostics, newProgram) + oldState.hasReusableDiagnostic ? convertToDiagnostics(emitDiagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(emitDiagnostics, newProgram) ); } if (canCopySemanticDiagnostics) { - if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) - return; - if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) - return; + if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) return; + if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { state.semanticDiagnosticsPerFile.set( sourceFilePath, - oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, sourceFilePath, newProgram) : repopulateDiagnostics(diagnostics, newProgram) ); (state.semanticDiagnosticsFromOldState ?? (state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set())).add(sourceFilePath); } @@ -127708,10 +127789,8 @@ function createBuilderProgramState(newProgram, oldState) { } }); if (useOldState && forEachEntry(oldState.fileInfos, (info, sourceFilePath) => { - if (state.fileInfos.has(sourceFilePath)) - return false; - if (outFilePath || info.affectsGlobalScope) - return true; + if (state.fileInfos.has(sourceFilePath)) return false; + if (outFilePath || info.affectsGlobalScope) return true; state.buildInfoEmitPending = true; return false; })) { @@ -127759,11 +127838,9 @@ function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) ); } function repopulateDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return diagnostics; + if (!diagnostics.length) return diagnostics; return sameMap(diagnostics, (diag2) => { - if (isString(diag2.messageText)) - return diag2; + if (isString(diag2.messageText)) return diag2; const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { var _a; return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); @@ -127785,18 +127862,17 @@ function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); } -function convertToDiagnostics(diagnostics, newProgram) { - if (!diagnostics.length) - return emptyArray; +function convertToDiagnostics(diagnostics, diagnosticFilePath, newProgram) { + if (!diagnostics.length) return emptyArray; let buildInfoDirectory; return diagnostics.map((diagnostic) => { - const result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPathInBuildInfoDirectory); + const result = convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportsDeprecated = diagnostic.reportDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; const { relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToDiagnosticRelatedInformation(r, diagnosticFilePath, newProgram, toPathInBuildInfoDirectory)) : [] : void 0; return result; }); function toPathInBuildInfoDirectory(path) { @@ -127804,9 +127880,9 @@ function convertToDiagnostics(diagnostics, newProgram) { return toPath(path, buildInfoDirectory, newProgram.getCanonicalFileName); } } -function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { +function convertToDiagnosticRelatedInformation(diagnostic, diagnosticFilePath, newProgram, toPath3) { const { file } = diagnostic; - const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; + const sourceFile = file !== false ? newProgram.getSourceFileByPath(file ? toPath3(file) : diagnosticFilePath) : void 0; return { ...diagnostic, file: sourceFile, @@ -127843,8 +127919,7 @@ function restoreBuilderProgramEmitState(state, savedEmitState) { state.hasChangedEmitSignature = savedEmitState.hasChangedEmitSignature; state.buildInfoEmitPending = savedEmitState.buildInfoEmitPending; state.emitDiagnosticsPerFile = savedEmitState.emitDiagnosticsPerFile; - if (savedEmitState.changedFilesSet) - state.changedFilesSet = savedEmitState.changedFilesSet; + if (savedEmitState.changedFilesSet) state.changedFilesSet = savedEmitState.changedFilesSet; } function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath)); @@ -127895,28 +127970,22 @@ function getNextAffectedFile(state, cancellationToken, host) { ); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; - if (!state.seenAffectedFiles) - state.seenAffectedFiles = /* @__PURE__ */ new Set(); + if (!state.seenAffectedFiles) state.seenAffectedFiles = /* @__PURE__ */ new Set(); } } function clearAffectedFilesPendingEmit(state, emitOnlyDtsFiles) { var _a; - if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) - return; - if (!emitOnlyDtsFiles) - return state.affectedFilesPendingEmit = void 0; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return; + if (!emitOnlyDtsFiles) return state.affectedFilesPendingEmit = void 0; state.affectedFilesPendingEmit.forEach((emitKind, path) => { const pending = emitKind & 7 /* AllJs */; - if (!pending) - state.affectedFilesPendingEmit.delete(path); - else - state.affectedFilesPendingEmit.set(path, pending); + if (!pending) state.affectedFilesPendingEmit.delete(path); + else state.affectedFilesPendingEmit.set(path, pending); }); } function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { var _a; - if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) - return void 0; + if (!((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.affectedFilesPendingEmit, (emitKind, path) => { var _a2; const affectedFile = state.program.getSourceFileByPath(path); @@ -127926,16 +127995,13 @@ function getNextAffectedFilePendingEmit(state, emitOnlyDtsFiles) { } const seenKind = (_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath); let pendingKind = getPendingEmitKind(emitKind, seenKind); - if (emitOnlyDtsFiles) - pendingKind = pendingKind & 24 /* AllDts */; - if (pendingKind) - return { affectedFile, emitKind: pendingKind }; + if (emitOnlyDtsFiles) pendingKind = pendingKind & 24 /* AllDts */; + if (pendingKind) return { affectedFile, emitKind: pendingKind }; }); } function getNextPendingEmitDiagnosticsFile(state) { var _a; - if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) - return void 0; + if (!((_a = state.emitDiagnosticsPerFile) == null ? void 0 : _a.size)) return void 0; return forEachEntry(state.emitDiagnosticsPerFile, (diagnostics, path) => { var _a2; const affectedFile = state.program.getSourceFileByPath(path); @@ -127944,8 +128010,7 @@ function getNextPendingEmitDiagnosticsFile(state) { return void 0; } const seenKind = ((_a2 = state.seenEmittedFiles) == null ? void 0 : _a2.get(affectedFile.resolvedPath)) || 0 /* None */; - if (!(seenKind & 24 /* AllDts */)) - return { affectedFile, diagnostics, seenKind }; + if (!(seenKind & 24 /* AllDts */)) return { affectedFile, diagnostics, seenKind }; }); } function removeDiagnosticsOfLibraryFiles(state) { @@ -127969,8 +128034,7 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken ); return; } - if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) - return; + if (state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) return; handleDtsMayChangeOfReferencingExportOfAffectedFile( state, affectedFile, @@ -127978,7 +128042,7 @@ function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken host ); } -function handleDtsMayChangeOf(state, path, cancellationToken, host) { +function handleDtsMayChangeOf(state, path, invalidateJsFiles, cancellationToken, host) { removeSemanticDiagnosticsOf(state, path); if (!state.changedFilesSet.has(path)) { const program = Debug.checkDefined(state.program); @@ -127993,7 +128057,9 @@ function handleDtsMayChangeOf(state, path, cancellationToken, host) { /*useFileVersionAsSignature*/ true ); - if (getEmitDeclarations(state.compilerOptions)) { + if (invalidateJsFiles) { + addToAffectedFilesPendingEmit(state, path, getBuilderFileEmit(state.compilerOptions)); + } else if (getEmitDeclarations(state.compilerOptions)) { addToAffectedFilesPendingEmit(state, path, state.compilerOptions.declarationMap ? 24 /* AllDts */ : 8 /* Dts */); } } @@ -128012,10 +128078,9 @@ function isChangedSignature(state, path) { const newSignature = Debug.checkDefined(state.fileInfos.get(path)).signature; return newSignature !== oldSignature; } -function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host) { +function handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host) { var _a; - if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) - return false; + if (!((_a = state.fileInfos.get(filePath)) == null ? void 0 : _a.affectsGlobalScope)) return false; BuilderState.getAllFilesExcludingDefaultLibraryFile( state, state.program, @@ -128025,6 +128090,7 @@ function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, hos (file) => handleDtsMayChangeOf( state, file.resolvedPath, + invalidateJsFiles, cancellationToken, host ) @@ -128033,11 +128099,9 @@ function handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, hos return true; } function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile, cancellationToken, host) { - var _a; - if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) - return; - if (!isChangedSignature(state, affectedFile.resolvedPath)) - return; + var _a, _b; + if (!state.referencedMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) return; + if (!isChangedSignature(state, affectedFile.resolvedPath)) return; if (getIsolatedModules(state.compilerOptions)) { const seenFileNamesMap = /* @__PURE__ */ new Map(); seenFileNamesMap.set(affectedFile.resolvedPath, true); @@ -128046,9 +128110,22 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile const currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { seenFileNamesMap.set(currentPath, true); - if (handleDtsMayChangeOfGlobalScope(state, currentPath, cancellationToken, host)) - return; - handleDtsMayChangeOf(state, currentPath, cancellationToken, host); + if (handleDtsMayChangeOfGlobalScope( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + )) return; + handleDtsMayChangeOf( + state, + currentPath, + /*invalidateJsFiles*/ + false, + cancellationToken, + host + ); if (isChangedSignature(state, currentPath)) { const currentSourceFile = Debug.checkDefined(state.program).getSourceFileByPath(currentPath); queue.push(...BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath)); @@ -128057,30 +128134,38 @@ function handleDtsMayChangeOfReferencingExportOfAffectedFile(state, affectedFile } } const seenFileAndExportsOfFile = /* @__PURE__ */ new Set(); - (_a = state.referencedMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _a.forEach((exportedFromPath) => { - if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, cancellationToken, host)) - return true; + const invalidateJsFiles = !!((_a = affectedFile.symbol) == null ? void 0 : _a.exports) && !!forEachEntry( + affectedFile.symbol.exports, + (exported) => { + if ((exported.flags & 128 /* ConstEnum */) !== 0) return true; + const aliased = skipAlias(exported, state.program.getTypeChecker()); + if (aliased === exported) return false; + return (aliased.flags & 128 /* ConstEnum */) !== 0 && some(aliased.declarations, (d) => getSourceFileOfNode(d) === affectedFile); + } + ); + (_b = state.referencedMap.getKeys(affectedFile.resolvedPath)) == null ? void 0 : _b.forEach((exportedFromPath) => { + if (handleDtsMayChangeOfGlobalScope(state, exportedFromPath, invalidateJsFiles, cancellationToken, host)) return true; const references = state.referencedMap.getKeys(exportedFromPath); return references && forEachKey(references, (filePath) => handleDtsMayChangeOfFileAndExportsOfFile( state, filePath, + invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host )); }); } -function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, cancellationToken, host) { +function handleDtsMayChangeOfFileAndExportsOfFile(state, filePath, invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host) { var _a; - if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) - return void 0; - if (handleDtsMayChangeOfGlobalScope(state, filePath, cancellationToken, host)) - return true; - handleDtsMayChangeOf(state, filePath, cancellationToken, host); + if (!tryAddToSet(seenFileAndExportsOfFile, filePath)) return void 0; + if (handleDtsMayChangeOfGlobalScope(state, filePath, invalidateJsFiles, cancellationToken, host)) return true; + handleDtsMayChangeOf(state, filePath, invalidateJsFiles, cancellationToken, host); (_a = state.referencedMap.getKeys(filePath)) == null ? void 0 : _a.forEach( (referencingFilePath) => handleDtsMayChangeOfFileAndExportsOfFile( state, referencingFilePath, + invalidateJsFiles, seenFileAndExportsOfFile, cancellationToken, host @@ -128113,12 +128198,13 @@ function isProgramBundleEmitBuildInfo(info) { return !!((_a = info.options) == null ? void 0 : _a.outFile); } function getBuildInfo2(state) { - var _a; + var _a, _b; const currentDirectory = Debug.checkDefined(state.program).getCurrentDirectory(); const buildInfoDirectory = getDirectoryPath(getNormalizedAbsolutePath(getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory)); const latestChangedDtsFile = state.latestChangedDtsFile ? relativeToBuildInfoEnsuringAbsolutePath(state.latestChangedDtsFile) : void 0; const fileNames = []; const fileNameToFileId = /* @__PURE__ */ new Map(); + const rootFileNames = new Set(state.program.getRootFileNames().map((f) => toPath(f, currentDirectory, state.program.getCanonicalFileName))); const root = []; if (state.compilerOptions.outFile) { const fileInfos2 = arrayFrom(state.fileInfos.entries(), ([key, value]) => { @@ -128130,6 +128216,7 @@ function getBuildInfo2(state) { fileNames, fileInfos: fileInfos2, root, + resolvedRoot: toResolvedRoot(), options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), outSignature: state.outSignature, latestChangedDtsFile, @@ -128148,7 +128235,7 @@ function getBuildInfo2(state) { let fileNamesToFileIdListId; let emitSignatures; const fileInfos = arrayFrom(state.fileInfos.entries(), ([key, value]) => { - var _a2, _b; + var _a2, _b2; const fileId = toFileId(key); tryAddRoot(key, fileId); Debug.assert(fileNames[fileId - 1] === relativeToBuildInfo(key)); @@ -128157,9 +128244,10 @@ function getBuildInfo2(state) { if (state.compilerOptions.composite) { const file = state.program.getSourceFileByPath(key); if (!isJsonSourceFile(file) && sourceFileMayBeEmitted(file, state.program)) { - const emitSignature = (_b = state.emitSignatures) == null ? void 0 : _b.get(key); + const emitSignature = (_b2 = state.emitSignatures) == null ? void 0 : _b2.get(key); if (emitSignature !== actualSignature) { - (emitSignatures || (emitSignatures = [])).push( + emitSignatures = append( + emitSignatures, emitSignature === void 0 ? fileId : ( // There is no emit, encode as false // fileId, signature: emptyArray if signature only differs in dtsMap option than our own compilerOptions otherwise EmitSignature @@ -128190,24 +128278,24 @@ function getBuildInfo2(state) { ); }); let referencedMap; - if (state.referencedMap) { + if ((_a = state.referencedMap) == null ? void 0 : _a.size()) { referencedMap = arrayFrom(state.referencedMap.keys()).sort(compareStringsCaseSensitive).map((key) => [ toFileId(key), toFileIdListId(state.referencedMap.getValues(key)) ]); } - const semanticDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(state.semanticDiagnosticsPerFile); + const semanticDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(); let affectedFilesPendingEmit; - if ((_a = state.affectedFilesPendingEmit) == null ? void 0 : _a.size) { + if ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.size) { const fullEmitForOptions = getBuilderFileEmit(state.compilerOptions); const seenFiles = /* @__PURE__ */ new Set(); for (const path of arrayFrom(state.affectedFilesPendingEmit.keys()).sort(compareStringsCaseSensitive)) { if (tryAddToSet(seenFiles, path)) { const file = state.program.getSourceFileByPath(path); - if (!file || !sourceFileMayBeEmitted(file, state.program)) - continue; + if (!file || !sourceFileMayBeEmitted(file, state.program)) continue; const fileId = toFileId(path), pendingEmit = state.affectedFilesPendingEmit.get(path); - (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push( + affectedFilesPendingEmit = append( + affectedFilesPendingEmit, pendingEmit === fullEmitForOptions ? fileId : ( // Pending full emit per options pendingEmit === 8 /* Dts */ ? [fileId] : ( @@ -128223,14 +128311,15 @@ function getBuildInfo2(state) { let changeFileSet; if (state.changedFilesSet.size) { for (const path of arrayFrom(state.changedFilesSet.keys()).sort(compareStringsCaseSensitive)) { - (changeFileSet || (changeFileSet = [])).push(toFileId(path)); + changeFileSet = append(changeFileSet, toFileId(path)); } } - const emitDiagnosticsPerFile = convertToProgramBuildInfoDiagnostics(state.emitDiagnosticsPerFile); + const emitDiagnosticsPerFile = convertToProgramBuildInfoEmitDiagnostics(); const program = { fileNames, fileInfos, root, + resolvedRoot: toResolvedRoot(), options: convertToProgramBuildInfoCompilerOptions(state.compilerOptions), fileIdsList, referencedMap, @@ -128261,29 +128350,34 @@ function getBuildInfo2(state) { const key = fileIds.join(); let fileIdListId = fileNamesToFileIdListId == null ? void 0 : fileNamesToFileIdListId.get(key); if (fileIdListId === void 0) { - (fileIdsList || (fileIdsList = [])).push(fileIds); - (fileNamesToFileIdListId || (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length); + fileIdsList = append(fileIdsList, fileIds); + (fileNamesToFileIdListId ?? (fileNamesToFileIdListId = /* @__PURE__ */ new Map())).set(key, fileIdListId = fileIdsList.length); } return fileIdListId; } function tryAddRoot(path, fileId) { const file = state.program.getSourceFile(path); - if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */)) - return; - if (!root.length) - return root.push(fileId); + if (!state.program.getFileIncludeReasons().get(file.path).some((r) => r.kind === 0 /* RootFile */)) return; + if (!root.length) return root.push(fileId); const last2 = root[root.length - 1]; const isLastStartEnd = isArray(last2); - if (isLastStartEnd && last2[1] === fileId - 1) - return last2[1] = fileId; - if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1) - return root.push(fileId); + if (isLastStartEnd && last2[1] === fileId - 1) return last2[1] = fileId; + if (isLastStartEnd || root.length === 1 || last2 !== fileId - 1) return root.push(fileId); const lastButOne = root[root.length - 2]; - if (!isNumber(lastButOne) || lastButOne !== last2 - 1) - return root.push(fileId); + if (!isNumber(lastButOne) || lastButOne !== last2 - 1) return root.push(fileId); root[root.length - 2] = [lastButOne, fileId]; return root.length = root.length - 1; } + function toResolvedRoot() { + let result; + rootFileNames.forEach((path) => { + const file = state.program.getSourceFileByPath(path); + if (file && path !== file.resolvedPath) { + result = append(result, [toFileId(file.resolvedPath), toFileId(path)]); + } + }); + return result; + } function convertToProgramBuildInfoCompilerOptions(options) { let result; const { optionsNameMap } = getOptionsNameMap(); @@ -128312,39 +128406,53 @@ function getBuildInfo2(state) { } return value; } - function convertToProgramBuildInfoDiagnostics(diagnostics) { + function convertToProgramBuildInfoDiagnostics() { let result; - if (diagnostics) { - for (const key of arrayFrom(diagnostics.keys()).sort(compareStringsCaseSensitive)) { - const value = diagnostics.get(key); - (result || (result = [])).push( - value.length ? [ - toFileId(key), - convertToReusableDiagnostics(value) - ] : toFileId(key) - ); + state.fileInfos.forEach((_value, key) => { + var _a2; + const value = (_a2 = state.semanticDiagnosticsPerFile) == null ? void 0 : _a2.get(key); + if (!value) { + if (!state.changedFilesSet.has(key)) result = append(result, toFileId(key)); + } else if (value.length) { + result = append(result, [ + toFileId(key), + convertToReusableDiagnostics(value, key) + ]); } + }); + return result; + } + function convertToProgramBuildInfoEmitDiagnostics() { + var _a2; + let result; + if (!((_a2 = state.emitDiagnosticsPerFile) == null ? void 0 : _a2.size)) return result; + for (const key of arrayFrom(state.emitDiagnosticsPerFile.keys()).sort(compareStringsCaseSensitive)) { + const value = state.emitDiagnosticsPerFile.get(key); + result = append(result, [ + toFileId(key), + convertToReusableDiagnostics(value, key) + ]); } return result; } - function convertToReusableDiagnostics(diagnostics) { + function convertToReusableDiagnostics(diagnostics, diagnosticFilePath) { Debug.assert(!!diagnostics.length); return diagnostics.map((diagnostic) => { - const result = convertToReusableDiagnosticRelatedInformation(diagnostic); + const result = convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath); result.reportsUnnecessary = diagnostic.reportsUnnecessary; result.reportDeprecated = diagnostic.reportsDeprecated; result.source = diagnostic.source; result.skippedOn = diagnostic.skippedOn; const { relatedInformation } = diagnostic; - result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r)) : [] : void 0; + result.relatedInformation = relatedInformation ? relatedInformation.length ? relatedInformation.map((r) => convertToReusableDiagnosticRelatedInformation(r, diagnosticFilePath)) : [] : void 0; return result; }); } - function convertToReusableDiagnosticRelatedInformation(diagnostic) { + function convertToReusableDiagnosticRelatedInformation(diagnostic, diagnosticFilePath) { const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + file: file ? file.resolvedPath === diagnosticFilePath ? void 0 : relativeToBuildInfo(file.resolvedPath) : false, messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } @@ -128359,12 +128467,10 @@ function getBuildInfo2(state) { return next === chain.next ? chain : { ...chain, next }; } function convertToReusableDiagnosticMessageChainArray(array) { - if (!array) - return array; + if (!array) return array; return forEach(array, (chain, index) => { const reusable = convertToReusableDiagnosticMessageChain(chain); - if (chain === reusable) - return void 0; + if (chain === reusable) return void 0; const result = index > 0 ? array.slice(0, index - 1) : []; result.push(reusable); for (let i = index + 1; i < array.length; i++) { @@ -128423,10 +128529,8 @@ function computeSignatureWithDiagnostics(program, sourceFile, text, host, data) return isString(diagnostic) ? diagnostic : diagnostic === void 0 ? "" : !diagnostic.next ? diagnostic.messageText : diagnostic.messageText + diagnostic.next.map(flattenDiagnosticMessageText2).join("\n"); } function locationInfo(diagnostic) { - if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) - return `(${diagnostic.start},${diagnostic.length})`; - if (sourceFileDirectory === void 0) - sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); + if (diagnostic.file.resolvedPath === sourceFile.resolvedPath) return `(${diagnostic.start},${diagnostic.length})`; + if (sourceFileDirectory === void 0) sourceFileDirectory = getDirectoryPath(sourceFile.resolvedPath); return `${ensurePathIsNonModuleName(getRelativePathFromDirectory( sourceFileDirectory, diagnostic.file.resolvedPath, @@ -128494,8 +128598,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa affected: pendingForDiagnostics.affectedFile }; } - if (!state.buildInfoEmitPending) - return void 0; + if (!state.buildInfoEmitPending) return void 0; const affected2 = state.program; const result2 = affected2.emitBuildInfo(writeFile2 || maybeBind(host, host.writeFile), cancellationToken); state.buildInfoEmitPending = false; @@ -128503,21 +128606,16 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa } ({ affectedFile: affected, emitKind } = pendingAffectedFile); } else { - if (!state.programEmitPending) - return void 0; + if (!state.programEmitPending) return void 0; emitKind = state.programEmitPending; - if (emitOnlyDtsFiles) - emitKind = emitKind & 24 /* AllDts */; - if (!emitKind) - return void 0; + if (emitOnlyDtsFiles) emitKind = emitKind & 24 /* AllDts */; + if (!emitKind) return void 0; affected = state.program; } } let emitOnly; - if (emitKind & 7 /* AllJs */) - emitOnly = 0 /* Js */; - if (emitKind & 24 /* AllDts */) - emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; + if (emitKind & 7 /* AllJs */) emitOnly = 0 /* Js */; + if (emitKind & 24 /* AllDts */) emitOnly = emitOnly === void 0 ? 1 /* Dts */ : void 0; if (affected === state.program) { state.programEmitPending = state.changedFilesSet.size ? getPendingEmitKind(programEmitKind, emitKind) : state.programEmitPending ? getPendingEmitKind(state.programEmitPending, emitKind) : void 0; } @@ -128531,27 +128629,22 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa if (affected !== state.program) { const affectedSourceFile = affected; state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); - if (state.affectedFilesIndex !== void 0) - state.affectedFilesIndex++; + if (state.affectedFilesIndex !== void 0) state.affectedFilesIndex++; state.buildInfoEmitPending = true; const existing = ((_a = state.seenEmittedFiles) == null ? void 0 : _a.get(affectedSourceFile.resolvedPath)) || 0 /* None */; (state.seenEmittedFiles ?? (state.seenEmittedFiles = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, emitKind | existing); const existingPending = ((_b = state.affectedFilesPendingEmit) == null ? void 0 : _b.get(affectedSourceFile.resolvedPath)) || programEmitKind; const pendingKind = getPendingEmitKind(existingPending, emitKind | existing); - if (pendingKind) - (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); - else - (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); - if (result.diagnostics.length) - (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); + if (pendingKind) (state.affectedFilesPendingEmit ?? (state.affectedFilesPendingEmit = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, pendingKind); + else (_c = state.affectedFilesPendingEmit) == null ? void 0 : _c.delete(affectedSourceFile.resolvedPath); + if (result.diagnostics.length) (state.emitDiagnosticsPerFile ?? (state.emitDiagnosticsPerFile = /* @__PURE__ */ new Map())).set(affectedSourceFile.resolvedPath, result.diagnostics); } else { state.changedFilesSet.clear(); } return { result, affected }; } function getWriteFileCallback(writeFile2, customTransformers) { - if (!getEmitDeclarations(state.compilerOptions)) - return writeFile2 || maybeBind(host, host.writeFile); + if (!getEmitDeclarations(state.compilerOptions)) return writeFile2 || maybeBind(host, host.writeFile); return (fileName, text, writeByteOrderMark, onError, sourceFiles, data) => { var _a, _b, _c; if (isDeclarationFileName(fileName)) { @@ -128569,15 +128662,12 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa host, data ); - if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) - emitSignature = signature; + if (!((_a = data == null ? void 0 : data.diagnostics) == null ? void 0 : _a.length)) emitSignature = signature; if (signature !== file.version) { - if (host.storeSignatureInfo) - (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(file.resolvedPath, 1 /* StoredSignatureAtEmit */); + if (host.storeSignatureInfo) (state.signatureInfo ?? (state.signatureInfo = /* @__PURE__ */ new Map())).set(file.resolvedPath, 1 /* StoredSignatureAtEmit */); if (state.affectedFiles) { const existing = (_b = state.oldSignatures) == null ? void 0 : _b.get(file.resolvedPath); - if (existing === void 0) - (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); + if (existing === void 0) (state.oldSignatures ?? (state.oldSignatures = /* @__PURE__ */ new Map())).set(file.resolvedPath, info.signature || false); info.signature = signature; } else { info.signature = signature; @@ -128588,8 +128678,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa if (state.compilerOptions.composite) { const filePath = sourceFiles[0].resolvedPath; emitSignature = handleNewSignature((_c = state.emitSignatures) == null ? void 0 : _c.get(filePath), emitSignature); - if (!emitSignature) - return; + if (!emitSignature) return; (state.emitSignatures ?? (state.emitSignatures = /* @__PURE__ */ new Map())).set(filePath, emitSignature); } } else if (state.compilerOptions.composite) { @@ -128598,27 +128687,20 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa /*newSignature*/ void 0 ); - if (!newSignature) - return; + if (!newSignature) return; state.outSignature = newSignature; } } - if (writeFile2) - writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data); - else if (host.writeFile) - host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); - else - state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + if (writeFile2) writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else if (host.writeFile) host.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); + else state.program.writeFile(fileName, text, writeByteOrderMark, onError, sourceFiles, data); function handleNewSignature(oldSignatureFormat, newSignature) { const oldSignature = !oldSignatureFormat || isString(oldSignatureFormat) ? oldSignatureFormat : oldSignatureFormat[0]; newSignature ?? (newSignature = computeSignature(text, host, data)); if (newSignature === oldSignature) { - if (oldSignatureFormat === oldSignature) - return void 0; - else if (data) - data.differsOnlyInMap = true; - else - data = { differsOnlyInMap: true }; + if (oldSignatureFormat === oldSignature) return void 0; + else if (data) data.differsOnlyInMap = true; + else data = { differsOnlyInMap: true }; } else { state.hasChangedEmitSignature = true; state.latestChangedDtsFile = fileName; @@ -128632,8 +128714,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); } const result = handleNoEmitOptions(builderProgram, targetSourceFile, writeFile2, cancellationToken); - if (result) - return result; + if (result) return result; if (!targetSourceFile) { if (kind === 1 /* EmitAndSemanticDiagnosticsBuilderProgram */) { let sourceMaps = []; @@ -128669,8 +128750,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa while (true) { const affected = getNextAffectedFile(state, cancellationToken, host); let result; - if (!affected) - return void 0; + if (!affected) return void 0; else if (affected !== state.program) { const affectedSourceFile = affected; if (!ignoreSourceFile || !ignoreSourceFile(affectedSourceFile)) { @@ -128679,8 +128759,7 @@ function createBuilderProgram(kind, { newProgram, host, oldProgram, configFilePa state.seenAffectedFiles.add(affectedSourceFile.resolvedPath); state.affectedFilesIndex++; state.buildInfoEmitPending = true; - if (!result) - continue; + if (!result) continue; } else { result = state.program.getSemanticDiagnostics( /*sourceFile*/ @@ -128757,12 +128836,10 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos const path = toFilePath(index + 1); const stateFileInfo = toBuilderStateFileInfoForMultiEmit(fileInfo); fileInfos.set(path, stateFileInfo); - if (emitSignatures && stateFileInfo.signature) - emitSignatures.set(path, stateFileInfo.signature); + if (emitSignatures && stateFileInfo.signature) emitSignatures.set(path, stateFileInfo.signature); }); (_d = program.emitSignatures) == null ? void 0 : _d.forEach((value) => { - if (isNumber(value)) - emitSignatures.delete(toFilePath(value)); + if (isNumber(value)) emitSignatures.delete(toFilePath(value)); else { const key = toFilePath(value[0]); emitSignatures.set( @@ -128774,16 +128851,17 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos ); } }); + const changedFilesSet = new Set(map(program.changeFileSet, toFilePath)); const fullEmitForOptions = program.affectedFilesPendingEmit ? getBuilderFileEmit(program.options || {}) : void 0; state = { fileInfos, compilerOptions: program.options ? convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath) : {}, - referencedMap: toManyToManyPathMap(program.referencedMap), - semanticDiagnosticsPerFile: toPerFileDiagnostics(program.semanticDiagnosticsPerFile), - emitDiagnosticsPerFile: toPerFileDiagnostics(program.emitDiagnosticsPerFile), + referencedMap: toManyToManyPathMap(program.referencedMap, program.options ?? {}), + semanticDiagnosticsPerFile: toPerFileSemanticDiagnostics(program.semanticDiagnosticsPerFile, fileInfos, changedFilesSet), + emitDiagnosticsPerFile: toPerFileEmitDiagnostics(program.emitDiagnosticsPerFile), hasReusableDiagnostic: true, affectedFilesPendingEmit: program.affectedFilesPendingEmit && arrayToMap(program.affectedFilesPendingEmit, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => toBuilderFileEmit(value, fullEmitForOptions)), - changedFilesSet: new Set(map(program.changeFileSet, toFilePath)), + changedFilesSet, latestChangedDtsFile, emitSignatures: (emitSignatures == null ? void 0 : emitSignatures.size) ? emitSignatures : void 0 }; @@ -128825,16 +128903,27 @@ function createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, hos function toFilePathsSet(fileIdsListId) { return filePathsSetList[fileIdsListId - 1]; } - function toManyToManyPathMap(referenceMap) { - if (!referenceMap) { - return void 0; - } - const map2 = BuilderState.createManyToManyPathMap(); + function toManyToManyPathMap(referenceMap, options) { + const map2 = BuilderState.createReferencedMap(options); + if (!map2 || !referenceMap) return map2; referenceMap.forEach(([fileId, fileIdListId]) => map2.set(toFilePath(fileId), toFilePathsSet(fileIdListId))); return map2; } - function toPerFileDiagnostics(diagnostics) { - return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(isNumber(value) ? value : value[0]), (value) => isNumber(value) ? emptyArray : value[1]); + function toPerFileSemanticDiagnostics(diagnostics, fileInfos, changedFilesSet) { + const semanticDiagnostics = new Map( + mapDefinedIterator( + fileInfos.keys(), + (key) => !changedFilesSet.has(key) ? [key, emptyArray] : void 0 + ) + ); + diagnostics == null ? void 0 : diagnostics.forEach((value) => { + if (isNumber(value)) semanticDiagnostics.delete(toFilePath(value)); + else semanticDiagnostics.set(toFilePath(value[0]), value[1]); + }); + return semanticDiagnostics.size ? semanticDiagnostics : void 0; + } + function toPerFileEmitDiagnostics(diagnostics) { + return diagnostics && arrayToMap(diagnostics, (value) => toFilePath(value[0]), (value) => value[1]); } } function getBuildInfoFileVersionMap(program, buildInfoPath, host) { @@ -128842,7 +128931,8 @@ function getBuildInfoFileVersionMap(program, buildInfoPath, host) { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const fileInfos = /* @__PURE__ */ new Map(); let rootIndex = 0; - const roots = []; + const roots = /* @__PURE__ */ new Map(); + const resolvedRoots = new Map(program.resolvedRoot); program.fileInfos.forEach((fileInfo, index) => { const path = toPath(program.fileNames[index], buildInfoDirectory, getCanonicalFileName); const version2 = isString(fileInfo) ? fileInfo : fileInfo.version; @@ -128852,17 +128942,24 @@ function getBuildInfoFileVersionMap(program, buildInfoPath, host) { const fileId = index + 1; if (isArray(current)) { if (current[0] <= fileId && fileId <= current[1]) { - roots.push(path); - if (current[1] === fileId) - rootIndex++; + addRoot(fileId, path); + if (current[1] === fileId) rootIndex++; } } else if (current === fileId) { - roots.push(path); + addRoot(fileId, path); rootIndex++; } } }); return { fileInfos, roots }; + function addRoot(fileId, path) { + const root = resolvedRoots.get(fileId); + if (root) { + roots.set(toPath(program.fileNames[root - 1], buildInfoDirectory, getCanonicalFileName), path); + } else { + roots.set(path, void 0); + } + } } function createRedirectedBuilderProgram(getState, configFileParsingDiagnostics) { return { @@ -128912,14 +129009,12 @@ function removeIgnoredPath(path) { return some(ignoredPaths, (searchPath) => path.includes(searchPath)) ? void 0 : path; } function perceivedOsRootLengthForWatching(pathComponents2, length2) { - if (length2 <= 1) - return 1; + if (length2 <= 1) return 1; let indexAfterOsRoot = 1; let isDosStyle = pathComponents2[0].search(/[a-zA-Z]:/) === 0; if (pathComponents2[0] !== directorySeparator && !isDosStyle && // Non dos style paths pathComponents2[1].search(/[a-zA-Z]\$$/) === 0) { - if (length2 === 2) - return 2; + if (length2 === 2) return 2; indexAfterOsRoot = 2; isDosStyle = true; } @@ -128932,10 +129027,8 @@ function perceivedOsRootLengthForWatching(pathComponents2, length2) { return indexAfterOsRoot + 2; } function canWatchDirectoryOrFile(pathComponents2, length2) { - if (length2 === void 0) - length2 = pathComponents2.length; - if (length2 <= 2) - return false; + if (length2 === void 0) length2 = pathComponents2.length; + if (length2 <= 2) return false; const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2); return length2 > perceivedOsRootLength + 1; } @@ -128943,11 +129036,9 @@ function canWatchAtTypes(atTypes) { return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes)); } function isInDirectoryPath(dirComponents, fileOrDirComponents) { - if (fileOrDirComponents.length < fileOrDirComponents.length) - return false; + if (fileOrDirComponents.length < fileOrDirComponents.length) return false; for (let i = 0; i < dirComponents.length; i++) { - if (fileOrDirComponents[i] !== dirComponents[i]) - return false; + if (fileOrDirComponents[i] !== dirComponents[i]) return false; } return true; } @@ -128962,11 +129053,9 @@ function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLoo failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); const failedLookupComponents = getPathComponents(failedLookupLocation); const perceivedOsRootLength = perceivedOsRootLengthForWatching(failedLookupPathComponents, failedLookupPathComponents.length); - if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) - return void 0; + if (failedLookupPathComponents.length <= perceivedOsRootLength + 1) return void 0; const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules"); - if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) - return void 0; + if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) return void 0; const lastNodeModulesIndex = failedLookupPathComponents.lastIndexOf("node_modules"); if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { if (failedLookupPathComponents.length > rootPathComponents.length + 1) { @@ -129306,10 +129395,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW fileWatchesOfAffectingLocations.get(existing[i]).files--; } } - if (expected) - impliedFormatPackageJsons.set(newFile.resolvedPath, newFile.packageJsonLocations); - else - impliedFormatPackageJsons.delete(newFile.resolvedPath); + if (expected) impliedFormatPackageJsons.set(newFile.resolvedPath, newFile.packageJsonLocations); + else impliedFormatPackageJsons.delete(newFile.resolvedPath); }); impliedFormatPackageJsons.forEach((existing, path) => { const newFile = newProgram == null ? void 0 : newProgram.getSourceFileByPath(path); @@ -129530,8 +129617,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW /*mode*/ void 0 ); - if (resolution && !resolution.isInvalidated) - return resolution; + if (resolution && !resolution.isInvalidated) return resolution; const data = (_a = resolutionHost.beforeResolveSingleModuleNameWithoutWatching) == null ? void 0 : _a.call(resolutionHost, moduleResolutionCache); const host = getModuleResolutionHost(resolutionHost); const result = resolveModuleName( @@ -129564,8 +129650,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if (resolved && resolved.resolvedFileName) { const key = resolutionHost.toPath(resolved.resolvedFileName); let resolutions = resolvedFileToResolution.get(key); - if (!resolutions) - resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); + if (!resolutions) resolvedFileToResolution.set(key, resolutions = /* @__PURE__ */ new Set()); resolutions.add(resolution); } } @@ -129596,18 +129681,15 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); const { failedLookupLocations, affectingLocations, alternateResult } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) - return; - if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) - resolutionsWithFailedLookups.add(resolution); + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !alternateResult) return; + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || alternateResult) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - if (alternateResult) - setAtRoot = watchFailedLookupLocation(alternateResult, setAtRoot); + if (alternateResult) setAtRoot = watchFailedLookupLocation(alternateResult, setAtRoot); if (setAtRoot) { setDirectoryWatcher( rootDir, @@ -129625,10 +129707,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); const { affectingLocations } = resolution; - if (!(affectingLocations == null ? void 0 : affectingLocations.length)) - return; - if (addToResolutionsWithOnlyAffectingLocations) - resolutionsWithOnlyAffectingLocations.add(resolution); + if (!(affectingLocations == null ? void 0 : affectingLocations.length)) return; + if (addToResolutionsWithOnlyAffectingLocations) resolutionsWithOnlyAffectingLocations.add(resolution); for (const affectingLocation of affectingLocations) { createFileWatcherOfAffectingLocation( affectingLocation, @@ -129640,10 +129720,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function createFileWatcherOfAffectingLocation(affectingLocation, forResolution) { const fileWatcher = fileWatchesOfAffectingLocations.get(affectingLocation); if (fileWatcher) { - if (forResolution) - fileWatcher.resolutions++; - else - fileWatcher.files++; + if (forResolution) fileWatcher.resolutions++; + else fileWatcher.files++; return; } let locationToWatch = affectingLocation; @@ -129670,8 +129748,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW symlinks: void 0 }; fileWatchesOfAffectingLocations.set(locationToWatch, watcher); - if (isSymlink) - symlinkWatcher = watcher; + if (isSymlink) symlinkWatcher = watcher; } if (isSymlink) { Debug.assert(!!symlinkWatcher); @@ -129697,10 +129774,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function invalidateAffectingFileWatcher(path, packageJsonMap) { var _a; const watcher = fileWatchesOfAffectingLocations.get(path); - if (watcher == null ? void 0 : watcher.resolutions) - (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); - if (watcher == null ? void 0 : watcher.files) - (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.resolutions) (affectingPathChecks ?? (affectingPathChecks = /* @__PURE__ */ new Set())).add(path); + if (watcher == null ? void 0 : watcher.files) (affectingPathChecksForFile ?? (affectingPathChecksForFile = /* @__PURE__ */ new Set())).add(path); (_a = watcher == null ? void 0 : watcher.symlinks) == null ? void 0 : _a.forEach((path2) => invalidateAffectingFileWatcher(path2, packageJsonMap)); packageJsonMap == null ? void 0 : packageJsonMap.delete(resolutionHost.toPath(path)); } @@ -129755,8 +129830,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW watcher: createDirPathToWatcher(), refCount: 1 }); - if (isSymlink) - dirPathToSymlinkPackageRefCount.set(dirPath, (dirPathToSymlinkPackageRefCount.get(dirPath) ?? 0) + 1); + if (isSymlink) dirPathToSymlinkPackageRefCount.set(dirPath, (dirPathToSymlinkPackageRefCount.get(dirPath) ?? 0) + 1); } function createDirPathToWatcher() { return isSymlink ? createOrAddRefToDirectoryWatchOfFailedLookups(packageDir, packageDirPath, nonRecursive) : createOrAddRefToDirectoryWatchOfFailedLookups(dir, dirPath, nonRecursive); @@ -129808,8 +129882,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW dirPathToSymlinkPackageRefCount.set(dirPath, refCount); } } - if (syncDirWatcherRemove) - closePackageDirWatcher(packageDirWatcher, packageDirPath); + if (syncDirWatcherRemove) closePackageDirWatcher(packageDirWatcher, packageDirPath); } } else { removeDirectoryWatcher(dirPath, syncDirWatcherRemove); @@ -129827,8 +129900,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if (resolved && resolved.resolvedFileName) { const key = resolutionHost.toPath(resolved.resolvedFileName); const resolutions = resolvedFileToResolution.get(key); - if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) - resolvedFileToResolution.delete(key); + if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } const { failedLookupLocations, affectingLocations, alternateResult } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { @@ -129838,10 +129910,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot, syncDirWatcherRemove); } } - if (alternateResult) - removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot, syncDirWatcherRemove); - if (removeAtRoot) - removeDirectoryWatcher(rootPath, syncDirWatcherRemove); + if (alternateResult) removeAtRoot = stopWatchFailedLookupLocation(alternateResult, removeAtRoot, syncDirWatcherRemove); + if (removeAtRoot) removeDirectoryWatcher(rootPath, syncDirWatcherRemove); } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -129849,16 +129919,14 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW for (const affectingLocation of affectingLocations) { const watcher = fileWatchesOfAffectingLocations.get(affectingLocation); watcher.resolutions--; - if (syncDirWatcherRemove) - closeFileWatcherOfAffectingLocation(watcher, affectingLocation); + if (syncDirWatcherRemove) closeFileWatcherOfAffectingLocation(watcher, affectingLocation); } } } function removeDirectoryWatcher(dirPath, syncDirWatcherRemove) { const dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); dirWatcher.refCount--; - if (syncDirWatcherRemove) - closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); + if (syncDirWatcherRemove) closeDirectoryWatchesOfFailedLookup(dirWatcher, dirPath); } function createDirectoryWatcher(directory, dirPath, nonRecursive) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, (fileOrDirectory) => { @@ -129884,14 +129952,11 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } } function removeResolutionsFromProjectReferenceRedirects(filePath) { - if (!fileExtensionIs(filePath, ".json" /* Json */)) - return; + if (!fileExtensionIs(filePath, ".json" /* Json */)) return; const program = resolutionHost.getCurrentProgram(); - if (!program) - return; + if (!program) return; const resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath); - if (!resolvedProjectReference) - return; + if (!resolvedProjectReference) return; resolvedProjectReference.commandLine.fileNames.forEach((f) => removeResolutionsOfFile(resolutionHost.toPath(f))); } function removeResolutionsOfFile(filePath, syncDirWatcherRemove) { @@ -129899,12 +129964,10 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective, syncDirWatcherRemove); } function invalidateResolutions(resolutions, canInvalidate) { - if (!resolutions) - return false; + if (!resolutions) return false; let invalidated = false; resolutions.forEach((resolution) => { - if (resolution.isInvalidated || !canInvalidate(resolution)) - return; + if (resolution.isInvalidated || !canInvalidate(resolution)) return; resolution.isInvalidated = invalidated = true; for (const containingFilePath of Debug.checkDefined(resolution.files)) { (filesWithInvalidatedResolutions ?? (filesWithInvalidatedResolutions = /* @__PURE__ */ new Set())).add(containingFilePath); @@ -129929,8 +129992,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW (isInDirectoryChecks || (isInDirectoryChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); } else { const updatedPath = removeIgnoredPath(fileOrDirectoryPath); - if (!updatedPath) - return false; + if (!updatedPath) return false; fileOrDirectoryPath = updatedPath; if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) { return false; @@ -129952,8 +130014,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW /*isFolder*/ true ); - if (packagePath) - (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); + if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); @@ -130002,10 +130063,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } function canInvalidateFailedLookupResolution(resolution) { var _a; - if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) - return true; - if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) - return false; + if (canInvalidatedFailedLookupResolutionWithAffectingLocation(resolution)) return true; + if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.alternateResult && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.alternateResult)); } function isInvalidatedFailedLookup(locationPath) { @@ -130060,8 +130119,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } } function canWatchTypeRootPath(typeRoot) { - if (resolutionHost.getCompilationSettings().typeRoots) - return true; + if (resolutionHost.getCompilationSettings().typeRoots) return true; return canWatchAtTypes(resolutionHost.toPath(typeRoot)); } } @@ -130145,8 +130203,7 @@ function getErrorCountForSummary(diagnostics) { function getFilesInErrorForSummary(diagnostics) { const filesInError = filter(diagnostics, (diagnostic) => diagnostic.category === 1 /* Error */).map( (errorDiagnostic) => { - if (errorDiagnostic.file === void 0) - return; + if (errorDiagnostic.file === void 0) return; return `${errorDiagnostic.file.fileName}`; } ); @@ -130180,8 +130237,7 @@ function prettyPathForFileError(error2, cwd) { return error2.fileName + line; } function getErrorSummaryText(errorCount, filesInError, newLine, host) { - if (errorCount === 0) - return ""; + if (errorCount === 0) return ""; const nonNilFiles = filesInError.filter((fileInError) => fileInError !== void 0); const distinctFileNamesWithLines = nonNilFiles.map((fileInError) => `${fileInError.fileName}:${fileInError.line}`).filter((value, index, self) => self.indexOf(value) === index); const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory()); @@ -130197,8 +130253,7 @@ function getErrorSummaryText(errorCount, filesInError, newLine, host) { } function createTabularErrorsDisplay(filesInError, host) { const distinctFiles = filesInError.filter((value, index, self) => index === self.findIndex((file) => (file == null ? void 0 : file.fileName) === (value == null ? void 0 : value.fileName))); - if (distinctFiles.length === 0) - return ""; + if (distinctFiles.length === 0) return ""; const numberLength = (num) => Math.log(num) * Math.LOG10E + 1; const fileToErrorCount = distinctFiles.map((file) => [file, countWhere(filesInError, (fileInError) => fileInError.fileName === file.fileName)]); const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0); @@ -130295,8 +130350,7 @@ function explainIfFileIsRedirectAndImpliedFormat(file, options, fileNameConverto function getMatchedFileSpec(program, fileName) { var _a; const configFile = program.getCompilerOptions().configFile; - if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) - return void 0; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedFilesSpec)) return void 0; const filePath = program.getCanonicalFileName(fileName); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); const index = findIndex(configFile.configFileSpecs.validatedFilesSpec, (fileSpec) => program.getCanonicalFileName(getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); @@ -130305,16 +130359,13 @@ function getMatchedFileSpec(program, fileName) { function getMatchedIncludeSpec(program, fileName) { var _a, _b; const configFile = program.getCompilerOptions().configFile; - if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) - return void 0; - if (configFile.configFileSpecs.isDefaultIncludeSpec) - return true; + if (!((_a = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _a.validatedIncludeSpecs)) return void 0; + if (configFile.configFileSpecs.isDefaultIncludeSpec) return true; const isJsonFile = fileExtensionIs(fileName, ".json" /* Json */); const basePath = getDirectoryPath(getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory())); const useCaseSensitiveFileNames2 = program.useCaseSensitiveFileNames(); const index = findIndex((_b = configFile == null ? void 0 : configFile.configFileSpecs) == null ? void 0 : _b.validatedIncludeSpecs, (includeSpec) => { - if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) - return false; + if (isJsonFile && !endsWith(includeSpec, ".json" /* Json */)) return false; const pattern = getPatternFromSpec(includeSpec, basePath, "files"); return !!pattern && getRegexFromPattern(`(${pattern})$`, useCaseSensitiveFileNames2).test(fileName); }); @@ -130363,20 +130414,18 @@ function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { } switch (reason.kind) { case 0 /* RootFile */: - if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Root_file_specified_for_compilation - ); + if (!((_a = options.configFile) == null ? void 0 : _a.configFileSpecs)) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Root_file_specified_for_compilation + ); const fileName = getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory()); const matchedByFiles = getMatchedFileSpec(program, fileName); - if (matchedByFiles) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Part_of_files_list_in_tsconfig_json - ); + if (matchedByFiles) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Part_of_files_list_in_tsconfig_json + ); const matchedByInclude = getMatchedIncludeSpec(program, fileName); return isString(matchedByInclude) ? chainDiagnosticMessages( /*details*/ @@ -130412,13 +130461,12 @@ function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) { ); } case 6 /* LibFile */: { - if (reason.index !== void 0) - return chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.Library_0_specified_in_compilerOptions, - options.lib[reason.index] - ); + if (reason.index !== void 0) return chainDiagnosticMessages( + /*details*/ + void 0, + Diagnostics.Library_0_specified_in_compilerOptions, + options.lib[reason.index] + ); const target = getNameOfScriptTarget(getEmitScriptTarget(options)); const messageAndArgs = target ? [Diagnostics.Default_library_for_target_0, target] : [Diagnostics.Default_library]; return chainDiagnosticMessages( @@ -130715,27 +130763,23 @@ function performIncrementalCompilation(input) { (s) => host.trace && host.trace(s), input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : void 0 ); - if (input.afterProgramEmitAndDiagnostics) - input.afterProgramEmitAndDiagnostics(builderProgram); + if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram); return exitStatus; } // src/compiler/watchPublic.ts function readBuilderProgram(compilerOptions, host) { const buildInfoPath = getTsBuildInfoEmitOutputFilePath(compilerOptions); - if (!buildInfoPath) - return void 0; + if (!buildInfoPath) return void 0; let buildInfo; if (host.getBuildInfo) { buildInfo = host.getBuildInfo(buildInfoPath, compilerOptions.configFilePath); } else { const content = host.readFile(buildInfoPath); - if (!content) - return void 0; + if (!content) return void 0; buildInfo = getBuildInfo(buildInfoPath, content); } - if (!buildInfo || buildInfo.version !== version || !buildInfo.program) - return void 0; + if (!buildInfo || buildInfo.version !== version || !buildInfo.program) return void 0; return createBuilderProgramUsingProgramBuildInfo(buildInfo, buildInfoPath, host); } function createIncrementalCompilerHost(options, system = sys) { @@ -130882,8 +130926,7 @@ function createWatchProgram(host) { builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); - if (configFileName) - updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); + if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; function close() { clearInvalidateResolutionsOfFailedLookupLocations(); @@ -130917,12 +130960,12 @@ function createWatchProgram(host) { var _a; (_a = config.watcher) == null ? void 0 : _a.close(); config.watcher = void 0; - if (config.watchedDirectories) - clearMap(config.watchedDirectories, closeFileWatcherOf); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); config.watchedDirectories = void 0; }); parsedConfigs = void 0; } + builderProgram = void 0; } function getResolutionCache() { return resolutionCache; @@ -130992,8 +131035,7 @@ function createWatchProgram(host) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); - if (projectReferences) - writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); + if (projectReferences) writeLog(` projectReferences: ${JSON.stringify(projectReferences)}`); const needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram(); hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -131090,10 +131132,8 @@ function createWatchProgram(host) { } function getSourceVersion(path, readFileWithCache) { const hostSourceFile = sourceFilesCache.get(path); - if (!hostSourceFile) - return void 0; - if (hostSourceFile.version) - return hostSourceFile.version; + if (!hostSourceFile) return void 0; + if (hostSourceFile.version) return hostSourceFile.version; const text = readFileWithCache(path); return text !== void 0 ? getSourceFileVersionAsHashFromText(compilerHost, text) : void 0; } @@ -131122,8 +131162,7 @@ function createWatchProgram(host) { return resolutionCache.hasChangedAutomaticTypeDirectiveNames(); } function clearInvalidateResolutionsOfFailedLookupLocations() { - if (!timerToInvalidateFailedLookupResolutions) - return false; + if (!timerToInvalidateFailedLookupResolutions) return false; host.clearTimeout(timerToInvalidateFailedLookupResolutions); timerToInvalidateFailedLookupResolutions = void 0; return true; @@ -131232,8 +131271,7 @@ function createWatchProgram(host) { const configPath = toPath3(configFileName2); let config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); if (config) { - if (!config.updateLevel) - return config.parsedCommandLine; + if (!config.updateLevel) return config.parsedCommandLine; if (config.parsedCommandLine && config.updateLevel === 1 /* RootNamesAndUpdate */ && !host.getParsedCommandLine) { writeLog("Reloading new file names and options"); Debug.assert(compilerOptions); @@ -131277,11 +131315,9 @@ function createWatchProgram(host) { var _a; const path = toPath3(fileName); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(path); - if (!config) - return; + if (!config) return; parsedConfigs.delete(path); - if (config.watchedDirectories) - clearMap(config.watchedDirectories, closeFileWatcherOf); + if (config.watchedDirectories) clearMap(config.watchedDirectories, closeFileWatcherOf); (_a = config.watcher) == null ? void 0 : _a.close(); clearSharedExtendedConfigFileWatcher(path, sharedExtendedConfigFileWatchers); } @@ -131350,8 +131386,7 @@ function createWatchProgram(host) { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 - })) - return; + })) return; if (updateLevel !== 2 /* Full */) { updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); @@ -131372,18 +131407,15 @@ function createWatchProgram(host) { (_fileName, eventKind) => { var _a; updateCachedSystemWithFile(extendedConfigFileName, extendedConfigFilePath, eventKind); - if (extendedConfigCache) - cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); + if (extendedConfigCache) cleanExtendedConfigCache(extendedConfigCache, extendedConfigFilePath, toPath3); const projects = (_a = sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a.projects; - if (!(projects == null ? void 0 : projects.size)) - return; + if (!(projects == null ? void 0 : projects.size)) return; projects.forEach((projectPath) => { if (configFileName && toPath3(configFileName) === projectPath) { updateLevel = 2 /* Full */; } else { const config = parsedConfigs == null ? void 0 : parsedConfigs.get(projectPath); - if (config) - config.updateLevel = 2 /* Full */; + if (config) config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(projectPath); } scheduleProgramUpdate(); @@ -131403,8 +131435,7 @@ function createWatchProgram(host) { (_fileName, eventKind) => { updateCachedSystemWithFile(configFileName2, configPath, eventKind); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (config) - config.updateLevel = 2 /* Full */; + if (config) config.updateLevel = 2 /* Full */; resolutionCache.removeResolutionsFromProjectReferenceRedirects(configPath); scheduleProgramUpdate(); }, @@ -131426,8 +131457,7 @@ function createWatchProgram(host) { } nextSourceFileVersion(fileOrDirectoryPath); const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); - if (!(config == null ? void 0 : config.parsedCommandLine)) - return; + if (!(config == null ? void 0 : config.parsedCommandLine)) return; if (isIgnoredFileFromWildCardWatching({ watchedDirPath: toPath3(directory), fileOrDirectory, @@ -131439,8 +131469,7 @@ function createWatchProgram(host) { useCaseSensitiveFileNames: useCaseSensitiveFileNames2, writeLog, toPath: toPath3 - })) - return; + })) return; if (config.updateLevel !== 2 /* Full */) { config.updateLevel = 1 /* RootNamesAndUpdate */; scheduleProgramUpdate(); @@ -131544,8 +131573,7 @@ function createSolutionBuilderWithWatchHost(system = sys, createProgram2, report function getCompilerOptionsOfBuildOptions(buildOptions) { const result = {}; commonOptionsWithBuild.forEach((option) => { - if (hasProperty(buildOptions, option.name)) - result[option.name] = buildOptions[option.name]; + if (hasProperty(buildOptions, option.name)) result[option.name] = buildOptions[option.name]; }); return result; } @@ -131696,8 +131724,7 @@ function toPath2(state, fileName) { function toResolvedConfigFilePath(state, fileName) { const { resolvedConfigFilePaths } = state; const path = resolvedConfigFilePaths.get(fileName); - if (path !== void 0) - return path; + if (path !== void 0) return path; const resolvedPath = toPath2(state, fileName); resolvedConfigFilePaths.set(fileName, resolvedPath); return resolvedPath; @@ -131721,8 +131748,7 @@ function parseConfigFile(state, configFileName, configFilePath) { let parsed; if (host.getParsedCommandLine) { parsed = host.getParsedCommandLine(configFileName); - if (!parsed) - diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName); + if (!parsed) diagnostic = createCompilerDiagnostic(Diagnostics.File_0_not_found, configFileName); } else { parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = (d) => diagnostic = d; parsed = getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions); @@ -131748,8 +131774,7 @@ function createBuildOrder(state, roots) { return circularDiagnostics ? { buildOrder: buildOrder || emptyArray, circularDiagnostics } : buildOrder || emptyArray; function visit(configFileName, inCircularContext) { const projPath = toResolvedConfigFilePath(state, configFileName); - if (permanentMarks.has(projPath)) - return; + if (permanentMarks.has(projPath)) return; if (temporaryMarks.has(projPath)) { if (!inCircularContext) { (circularDiagnostics || (circularDiagnostics = [])).push( @@ -131831,16 +131856,14 @@ function createStateBuildOrder(state) { function getBuildOrderFor(state, project, onlyReferences) { const resolvedProject = project && resolveProjectName(state, project); const buildOrderFromState = getBuildOrder(state); - if (isCircularBuildOrder(buildOrderFromState)) - return buildOrderFromState; + if (isCircularBuildOrder(buildOrderFromState)) return buildOrderFromState; if (resolvedProject) { const projectPath = toResolvedConfigFilePath(state, resolvedProject); const projectIndex = findIndex( buildOrderFromState, (configFileName) => toResolvedConfigFilePath(state, configFileName) === projectPath ); - if (projectIndex === -1) - return void 0; + if (projectIndex === -1) return void 0; } const buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState; Debug.assert(!isCircularBuildOrder(buildOrder)); @@ -131881,8 +131904,7 @@ function enableCache(state) { }; } function disableCache(state) { - if (!state.cache) - return; + if (!state.cache) return; const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; @@ -131910,11 +131932,9 @@ function addProjToQueue({ projectPendingBuild }, proj, updateLevel) { } } function setupInitialBuild(state, cancellationToken) { - if (!state.allProjectBuildPending) - return; + if (!state.allProjectBuildPending) return; state.allProjectBuildPending = false; - if (state.options.watch) - reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); + if (state.options.watch) reportWatchStatus(state, Diagnostics.Starting_compilation_in_watch_mode); enableCache(state); const buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state)); buildOrder.forEach( @@ -132013,8 +132033,7 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec if (step === 4 /* EmitBuildInfo */) { return emitBuildInfo(writeFile2, cancellationToken); } - if (step !== 3 /* Emit */) - return void 0; + if (step !== 3 /* Emit */) return void 0; return emit(writeFile2, cancellationToken, customTransformers); }, done @@ -132040,8 +132059,7 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec step = 5 /* QueueReferencingProjects */; return; } - if (state.options.verbose) - reportStatus(state, Diagnostics.Building_project_0, project); + if (state.options.verbose) reportStatus(state, Diagnostics.Building_project_0, project); if (config.fileNames.length === 0) { reportAndStoreErrors(state, projectPath, getConfigFileParsingDiagnostics(config)); buildResult = 0 /* None */; @@ -132164,12 +132182,10 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec outputFiles.forEach(({ name, text, writeByteOrderMark, data }) => { const path = toPath2(state, name); emittedOutputs.set(toPath2(state, name), name); - if (data == null ? void 0 : data.buildInfo) - setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); + if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, options, resultFlags); const modifiedTime = (data == null ? void 0 : data.differsOnlyInMap) ? getModifiedTime(state.host, name) : void 0; writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); - if (data == null ? void 0 : data.differsOnlyInMap) - state.host.setModifiedTime(name, modifiedTime); + if (data == null ? void 0 : data.differsOnlyInMap) state.host.setModifiedTime(name, modifiedTime); else if (!isIncremental && state.watch) { (outputTimeStampMap || (outputTimeStampMap = getOutputTimeStampMap(state, projectPath))).set(path, now || (now = getCurrentTime(state.host))); } @@ -132186,12 +132202,9 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec Debug.assertIsDefined(program); Debug.assert(step === 4 /* EmitBuildInfo */); const emitResult = program.emitBuildInfo((name, text, writeByteOrderMark, onError, sourceFiles, data) => { - if (data == null ? void 0 : data.buildInfo) - setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */); - if (writeFileCallback) - writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); - else - state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); + if (data == null ? void 0 : data.buildInfo) setBuildInfo(state, data.buildInfo, projectPath, program.getCompilerOptions(), 2 /* DeclarationOutputUnchanged */); + if (writeFileCallback) writeFileCallback(name, text, writeByteOrderMark, onError, sourceFiles, data); + else state.compilerHost.writeFile(name, text, writeByteOrderMark, onError, sourceFiles, data); }, cancellationToken); if (emitResult.diagnostics.length) { reportErrors(state, emitResult.diagnostics); @@ -132265,17 +132278,14 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec } } function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { - if (!state.projectPendingBuild.size) - return void 0; - if (isCircularBuildOrder(buildOrder)) - return void 0; + if (!state.projectPendingBuild.size) return void 0; + if (isCircularBuildOrder(buildOrder)) return void 0; const { options, projectPendingBuild } = state; for (let projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) { const project = buildOrder[projectIndex]; const projectPath = toResolvedConfigFilePath(state, project); const updateLevel = state.projectPendingBuild.get(projectPath); - if (updateLevel === void 0) - continue; + if (updateLevel === void 0) continue; if (reportQueue) { reportQueue = false; reportBuildQueue(state, buildOrder); @@ -132371,8 +132381,7 @@ function createInvalidatedProjectWithInfo(state, info, buildOrder) { } function getNextInvalidatedProject(state, buildOrder, reportQueue) { const info = getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue); - if (!info) - return info; + if (!info) return info; return createInvalidatedProjectWithInfo(state, info, buildOrder); } function listEmittedFile({ write }, proj, file) { @@ -132381,17 +132390,14 @@ function listEmittedFile({ write }, proj, file) { } } function getOldProgram({ options, builderPrograms, compilerHost }, proj, parsed) { - if (options.force) - return void 0; + if (options.force) return void 0; const value = builderPrograms.get(proj); - if (value) - return value; + if (value) return value; return readBuilderProgram(parsed.options, compilerHost); } function afterProgramDone(state, program) { if (program) { - if (state.write) - listFiles(program, state.write); + if (state.write) listFiles(program, state.write); if (state.host.afterProgramEmitAndDiagnostics) { state.host.afterProgramEmitAndDiagnostics(program); } @@ -132403,8 +132409,7 @@ function buildErrors(state, resolvedPath, program, config, diagnostics, buildRes const canEmitBuildInfo = program && !program.getCompilerOptions().outFile; reportAndStoreErrors(state, resolvedPath, diagnostics); state.projectStatus.set(resolvedPath, { type: 0 /* Unbuildable */, reason: `${errorType} errors` }); - if (canEmitBuildInfo) - return { buildResult, step: 4 /* EmitBuildInfo */ }; + if (canEmitBuildInfo) return { buildResult, step: 4 /* EmitBuildInfo */ }; afterProgramDone(state, program); return { buildResult, step: 5 /* QueueReferencingProjects */ }; } @@ -132415,17 +132420,13 @@ function getModifiedTime2(state, fileName) { const path = toPath2(state, fileName); const existing = state.filesWatched.get(path); if (state.watch && !!existing) { - if (!isFileWatcherWithModifiedTime(existing)) - return existing; - if (existing.modifiedTime) - return existing.modifiedTime; + if (!isFileWatcherWithModifiedTime(existing)) return existing; + if (existing.modifiedTime) return existing.modifiedTime; } const result = getModifiedTime(state.host, fileName); if (state.watch) { - if (existing) - existing.modifiedTime = result; - else - state.filesWatched.set(path, result); + if (existing) existing.modifiedTime = result; + else state.filesWatched.set(path, result); } return result; } @@ -132464,11 +132465,9 @@ function watchFile(state, file, callback, pollingInterval, options, watchType, p }; } function getOutputTimeStampMap(state, resolvedConfigFilePath) { - if (!state.watch) - return void 0; + if (!state.watch) return void 0; let result = state.outputTimeStamps.get(resolvedConfigFilePath); - if (!result) - state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); + if (!result) state.outputTimeStamps.set(resolvedConfigFilePath, result = /* @__PURE__ */ new Map()); return result; } function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags) { @@ -132478,8 +132477,7 @@ function setBuildInfo(state, buildInfo, resolvedConfigPath, options, resultFlags if (existing) { existing.buildInfo = buildInfo; existing.modifiedTime = modifiedTime; - if (!(resultFlags & 2 /* DeclarationOutputUnchanged */)) - existing.latestChangedDtsTime = modifiedTime; + if (!(resultFlags & 2 /* DeclarationOutputUnchanged */)) existing.latestChangedDtsTime = modifiedTime; } else { state.buildInfoCache.set(resolvedConfigPath, { path: toPath2(state, buildInfoPath), @@ -132516,7 +132514,7 @@ function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, } } function getUpToDateStatusWorker(state, project, resolvedPath) { - var _a, _b, _c; + var _a, _b, _c, _d; if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) { return { type: 15 /* ContainerOnly */ @@ -132547,12 +132545,10 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { upstreamProjectName: ref.path }; } - if (!force) - (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); + if (!force) (referenceStatuses || (referenceStatuses = [])).push({ ref, refStatus, resolvedRefPath, resolvedConfig }); } } - if (force) - return { type: 16 /* ForceBuild */ }; + if (force) return { type: 16 /* ForceBuild */ }; const { host } = state; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(project.options); let oldestOutputFileName; @@ -132590,7 +132586,7 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { }; } if (buildInfo.program) { - if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? ((_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length) || ((_c = buildInfo.program.emitDiagnosticsPerFile) == null ? void 0 : _c.length) : some(buildInfo.program.semanticDiagnosticsPerFile, isArray))) { + if (((_a = buildInfo.program.changeFileSet) == null ? void 0 : _a.length) || (!project.options.noEmit ? ((_b = buildInfo.program.affectedFilesPendingEmit) == null ? void 0 : _b.length) || ((_c = buildInfo.program.emitDiagnosticsPerFile) == null ? void 0 : _c.length) : (_d = buildInfo.program.semanticDiagnosticsPerFile) == null ? void 0 : _d.length)) { return { type: 7 /* OutOfDateBuildInfo */, buildInfoFile: buildInfoPath @@ -132619,17 +132615,17 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { reason: `${inputFile} does not exist` }; } + const inputPath = buildInfoProgram ? toPath2(state, inputFile) : void 0; if (buildInfoTime && buildInfoTime < inputTime) { let version2; let currentVersion; if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); - version2 = buildInfoVersionMap.fileInfos.get(toPath2(state, inputFile)); - const text = version2 ? state.readFileWithCache(inputFile) : void 0; + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + const resolvedInputPath = buildInfoVersionMap.roots.get(inputPath); + version2 = buildInfoVersionMap.fileInfos.get(resolvedInputPath ?? inputPath); + const text = version2 ? state.readFileWithCache(resolvedInputPath ?? inputFile) : void 0; currentVersion = text !== void 0 ? getSourceFileVersionAsHashFromText(host, text) : void 0; - if (version2 && version2 === currentVersion) - pseudoInputUpToDate = true; + if (version2 && version2 === currentVersion) pseudoInputUpToDate = true; } if (!version2 || version2 !== currentVersion) { return { @@ -132643,20 +132639,21 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { newestInputFileName = inputFile; newestInputFileTime = inputTime; } - if (buildInfoProgram) - seenRoots.add(toPath2(state, inputFile)); + if (buildInfoProgram) seenRoots.add(inputPath); } if (buildInfoProgram) { - if (!buildInfoVersionMap) - buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); - for (const existingRoot of buildInfoVersionMap.roots) { - if (!seenRoots.has(existingRoot)) { - return { - type: 9 /* OutOfDateRoots */, - buildInfoFile: buildInfoPath, - inputFile: existingRoot - }; - } + if (!buildInfoVersionMap) buildInfoVersionMap = getBuildInfoFileVersionMap(buildInfoProgram, buildInfoPath, host); + const existingRoot = forEachEntry( + buildInfoVersionMap.roots, + // File was root file when project was built but its not any more + (_resolved, existingRoot2) => !seenRoots.has(existingRoot2) ? existingRoot2 : void 0 + ); + if (existingRoot) { + return { + type: 9 /* OutOfDateRoots */, + buildInfoFile: buildInfoPath, + inputFile: existingRoot + }; } } if (!buildInfoPath) { @@ -132716,18 +132713,15 @@ function getUpToDateStatusWorker(state, project, resolvedPath) { } } const configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); - if (configStatus) - return configStatus; + if (configStatus) return configStatus; const extendedConfigStatus = forEach(project.options.configFile.extendedSourceFiles || emptyArray, (configFile) => checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName)); - if (extendedConfigStatus) - return extendedConfigStatus; + if (extendedConfigStatus) return extendedConfigStatus; const packageJsonLookups = state.lastCachedPackageJsonLookups.get(resolvedPath); const dependentPackageFileStatus = packageJsonLookups && forEachKey( packageJsonLookups, (path) => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName) ); - if (dependentPackageFileStatus) - return dependentPackageFileStatus; + if (dependentPackageFileStatus) return dependentPackageFileStatus; return { type: pseudoUpToDate ? 2 /* UpToDateWithUpstreamTypes */ : pseudoInputUpToDate ? 14 /* UpToDateWithInputFileText */ : 1 /* UpToDate */, newestInputFileTime, @@ -132755,14 +132749,12 @@ function getUpToDateStatus(state, project, resolvedPath) { return actual; } function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, skipOutputs) { - if (proj.options.noEmit) - return; + if (proj.options.noEmit) return; let now; const buildInfoPath = getTsBuildInfoEmitOutputFilePath(proj.options); if (buildInfoPath) { if (!(skipOutputs == null ? void 0 : skipOutputs.has(toPath2(state, buildInfoPath)))) { - if (!!state.options.verbose) - reportStatus(state, verboseMessage, proj.options.configFilePath); + if (!!state.options.verbose) reportStatus(state, verboseMessage, proj.options.configFilePath); state.host.setModifiedTime(buildInfoPath, now = getCurrentTime(state.host)); getBuildInfoCacheEntry(state, buildInfoPath, projectPath).modifiedTime = now; } @@ -132777,8 +132769,7 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, let reportVerbose = !!state.options.verbose; for (const file of outputs) { const path = toPath2(state, file); - if (skipOutputs == null ? void 0 : skipOutputs.has(path)) - continue; + if (skipOutputs == null ? void 0 : skipOutputs.has(path)) continue; if (reportVerbose) { reportVerbose = false; reportStatus(state, verboseMessage, proj.options.configFilePath); @@ -132791,16 +132782,13 @@ function updateOutputTimestampsWorker(state, proj, projectPath, verboseMessage, } } outputTimeStampMap == null ? void 0 : outputTimeStampMap.forEach((_value, key) => { - if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) - outputTimeStampMap.delete(key); + if (!(skipOutputs == null ? void 0 : skipOutputs.has(key)) && !modifiedOutputs.has(key)) outputTimeStampMap.delete(key); }); } function getLatestChangedDtsTime(state, options, resolvedConfigPath) { - if (!options.composite) - return void 0; + if (!options.composite) return void 0; const entry = Debug.checkDefined(state.buildInfoCache.get(resolvedConfigPath)); - if (entry.latestChangedDtsTime !== void 0) - return entry.latestChangedDtsTime || void 0; + if (entry.latestChangedDtsTime !== void 0) return entry.latestChangedDtsTime || void 0; const latestChangedDtsTime = entry.buildInfo && entry.buildInfo.program && entry.buildInfo.program.latestChangedDtsFile ? state.host.getModifiedTime(getNormalizedAbsolutePath(entry.buildInfo.program.latestChangedDtsFile, getDirectoryPath(entry.path))) : void 0; entry.latestChangedDtsTime = latestChangedDtsTime || false; return latestChangedDtsTime; @@ -132816,22 +132804,17 @@ function updateOutputTimestamps(state, proj, resolvedPath) { }); } function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) { - if (buildResult & 124 /* AnyErrors */) - return; - if (!config.options.composite) - return; + if (buildResult & 124 /* AnyErrors */) return; + if (!config.options.composite) return; for (let index = projectIndex + 1; index < buildOrder.length; index++) { const nextProject = buildOrder[index]; const nextProjectPath = toResolvedConfigFilePath(state, nextProject); - if (state.projectPendingBuild.has(nextProjectPath)) - continue; + if (state.projectPendingBuild.has(nextProjectPath)) continue; const nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath); - if (!nextProjectConfig || !nextProjectConfig.projectReferences) - continue; + if (!nextProjectConfig || !nextProjectConfig.projectReferences) continue; for (const ref of nextProjectConfig.projectReferences) { const resolvedRefPath = resolveProjectName(state, ref.path); - if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) - continue; + if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath) continue; const status = state.projectStatus.get(nextProjectPath); if (status) { switch (status.type) { @@ -132871,19 +132854,16 @@ function build(state, project, cancellationToken, writeFile2, getCustomTransform } function buildWorker(state, project, cancellationToken, writeFile2, getCustomTransformers, onlyReferences) { const buildOrder = getBuildOrderFor(state, project, onlyReferences); - if (!buildOrder) - return 3 /* InvalidProject_OutputsSkipped */; + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; setupInitialBuild(state, cancellationToken); let reportQueue = true; let successfulProjects = 0; while (true) { const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); - if (!invalidatedProject) - break; + if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken, writeFile2, getCustomTransformers == null ? void 0 : getCustomTransformers(invalidatedProject.project)); - if (!state.diagnostics.has(invalidatedProject.projectPath)) - successfulProjects++; + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } disableCache(state); reportErrorSummary(state, buildOrder); @@ -132899,8 +132879,7 @@ function clean(state, project, onlyReferences) { } function cleanWorker(state, project, onlyReferences) { const buildOrder = getBuildOrderFor(state, project, onlyReferences); - if (!buildOrder) - return 3 /* InvalidProject_OutputsSkipped */; + if (!buildOrder) return 3 /* InvalidProject_OutputsSkipped */; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); return 4 /* ProjectReferenceCycle_OutputsSkipped */; @@ -132915,12 +132894,10 @@ function cleanWorker(state, project, onlyReferences) { continue; } const outputs = getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames()); - if (!outputs.length) - continue; + if (!outputs.length) continue; const inputFileNames = new Set(parsed.fileNames.map((f) => toPath2(state, f))); for (const output of outputs) { - if (inputFileNames.has(toPath2(state, output))) - continue; + if (inputFileNames.has(toPath2(state, output))) continue; if (host.fileExists(output)) { if (filesToDelete) { filesToDelete.push(output); @@ -132975,8 +132952,7 @@ function buildNextInvalidatedProject(_timeoutType, state, changeDetected) { const buildOrder = buildNextInvalidatedProjectWorker(state, changeDetected); mark("SolutionBuilder::afterBuild"); measure("SolutionBuilder::Build", "SolutionBuilder::beforeBuild", "SolutionBuilder::afterBuild"); - if (buildOrder) - reportErrorSummary(state, buildOrder); + if (buildOrder) reportErrorSummary(state, buildOrder); } function buildNextInvalidatedProjectWorker(state, changeDetected) { state.timerToBuildInvalidatedProject = void 0; @@ -132997,16 +132973,14 @@ function buildNextInvalidatedProjectWorker(state, changeDetected) { invalidatedProject.done(); projectsBuilt++; while (state.projectPendingBuild.size) { - if (state.timerToBuildInvalidatedProject) - return; + if (state.timerToBuildInvalidatedProject) return; const info = getNextInvalidatedProjectCreateInfo( state, buildOrder, /*reportQueue*/ false ); - if (!info) - break; + if (!info) break; if (info.kind !== 1 /* UpdateOutputFileStamps */ && (changeDetected || projectsBuilt === 5)) { scheduleBuildInvalidatedProject( state, @@ -133018,16 +132992,14 @@ function buildNextInvalidatedProjectWorker(state, changeDetected) { } const project = createInvalidatedProjectWithInfo(state, info, buildOrder); project.done(); - if (info.kind !== 1 /* UpdateOutputFileStamps */) - projectsBuilt++; + if (info.kind !== 1 /* UpdateOutputFileStamps */) projectsBuilt++; } } disableCache(state); return buildOrder; } function watchConfigFile(state, resolved, resolvedPath, parsed) { - if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) - return; + if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath)) return; state.allWatchedConfigFiles.set( resolvedPath, watchFile( @@ -133061,8 +133033,7 @@ function watchExtendedConfigFiles(state, resolvedPath, parsed) { ); } function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; + if (!state.watch) return; updateWatchingWildcardDirectories( getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), parsed.wildcardDirectories, @@ -133081,8 +133052,7 @@ function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames, writeLog: (s) => state.writeLog(s), toPath: (fileName) => toPath2(state, fileName) - })) - return; + })) return; invalidateProjectAndScheduleBuilds(state, resolvedPath, 1 /* RootNamesAndUpdate */); }, flags, @@ -133093,8 +133063,7 @@ function watchWildCardDirectories(state, resolved, resolvedPath, parsed) { ); } function watchInputFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch) - return; + if (!state.watch) return; mutateMap( getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), new Set(parsed.fileNames), @@ -133113,8 +133082,7 @@ function watchInputFiles(state, resolved, resolvedPath, parsed) { ); } function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { - if (!state.watch || !state.lastCachedPackageJsonLookups) - return; + if (!state.watch || !state.lastCachedPackageJsonLookups) return; mutateMap( getOrCreateValueMapFromConfigFileMap(state.allWatchedPackageJsonFiles, resolvedPath), state.lastCachedPackageJsonLookups.get(resolvedPath), @@ -133133,8 +133101,7 @@ function watchPackageJsonFiles(state, resolved, resolvedPath, parsed) { ); } function startWatching(state, buildOrder) { - if (!state.watchAllProjectsPending) - return; + if (!state.watchAllProjectsPending) return; mark("SolutionBuilder::beforeWatcherCreation"); state.watchAllProjectsPending = false; for (const resolved of getBuildOrderFromAnyBuildOrder(buildOrder)) { @@ -133221,8 +133188,7 @@ function reportParseConfigFileDiagnostic(state, proj) { reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]); } function reportErrorSummary(state, buildOrder) { - if (!state.needsSummary) - return; + if (!state.needsSummary) return; state.needsSummary = false; const canReportSummary = state.watch || !!state.host.reportErrorSummary; const { diagnostics } = state; @@ -133231,10 +133197,8 @@ function reportErrorSummary(state, buildOrder) { if (isCircularBuildOrder(buildOrder)) { reportBuildQueue(state, buildOrder.buildOrder); reportErrors(state, buildOrder.circularDiagnostics); - if (canReportSummary) - totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics); - if (canReportSummary) - filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)]; + if (canReportSummary) totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics); + if (canReportSummary) filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)]; } else { buildOrder.forEach((project) => { const projectPath = toResolvedConfigFilePath(state, project); @@ -133242,10 +133206,8 @@ function reportErrorSummary(state, buildOrder) { reportErrors(state, diagnostics.get(projectPath) || emptyArray); } }); - if (canReportSummary) - diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors)); - if (canReportSummary) - diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => totalErrors += getErrorCountForSummary(singleProjectErrors)); + if (canReportSummary) diagnostics.forEach((singleProjectErrors) => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]); } if (state.watch) { reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors); @@ -133553,8 +133515,7 @@ function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) text.push(`${valueCandidates.valueType} ${valueCandidates.possibleValues}`); } if (defaultValueDescription) { - if (valueCandidates) - text.push(sys2.newLine); + if (valueCandidates) text.push(sys2.newLine); const diagType = getDiagnosticText(Diagnostics.default_Colon); text.push(`${diagType} ${defaultValueDescription}`); } @@ -133570,8 +133531,7 @@ function generateOptionOutput(sys2, option, rightAlignOfLeft, leftAlignOfRight) const ignoreValues = ["string"]; const ignoredDescriptions = [void 0, "false", "n/a"]; const defaultValueDescription2 = option2.defaultValueDescription; - if (option2.category === Diagnostics.Command_line_Options) - return false; + if (option2.category === Diagnostics.Command_line_Options) return false; if (contains(ignoreValues, valueCandidates2 == null ? void 0 : valueCandidates2.possibleValues) && contains(ignoredDescriptions, defaultValueDescription2)) { return false; } @@ -133907,8 +133867,7 @@ function executeCommandLineWorker(sys2, cb, commandLine) { configParseResult.options ); if (isWatchSet(configParseResult.options)) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; return createWatchOfConfigFile( sys2, cb, @@ -133944,8 +133903,7 @@ function executeCommandLineWorker(sys2, cb, commandLine) { commandLineOptions ); if (isWatchSet(commandLineOptions)) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; return createWatchOfFilesAndCompilerOptions( sys2, cb, @@ -134049,8 +134007,7 @@ function performBuild(sys2, cb, buildOptions, watchOptions, projects, errors) { return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); } if (buildOptions.watch) { - if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) - return; + if (reportWatchModeWithoutSysSupport(sys2, reportDiagnostic)) return; const buildHost2 = createSolutionBuilderWithWatchHost( sys2, /*createProgram*/ @@ -134255,10 +134212,8 @@ function createSolutionPerfomrance() { function addAggregateStatistic(s) { const existing = statistics == null ? void 0 : statistics.get(s.name); if (existing) { - if (existing.type === 2 /* memory */) - existing.value = Math.max(existing.value, s.value); - else - existing.value += s.value; + if (existing.type === 2 /* memory */) existing.value = Math.max(existing.value, s.value); + else existing.value += s.value; } else { (statistics ?? (statistics = /* @__PURE__ */ new Map())).set(s.name, s); } @@ -134271,8 +134226,7 @@ function createSolutionPerfomrance() { } } function reportSolutionBuilderTimes(builder, solutionPerformance) { - if (!solutionPerformance) - return; + if (!solutionPerformance) return; if (!isEnabled()) { sys.write(Diagnostics.Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found.message + "\n"); return; @@ -134289,8 +134243,7 @@ function reportSolutionBuilderTimes(builder, solutionPerformance) { statistics.push(s); }); forEachMeasure((name, duration) => { - if (isSolutionMarkOrMeasure(name)) - statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ }); + if (isSolutionMarkOrMeasure(name)) statistics.push({ name: `${getNameFromSolutionBuilderMarkOrMeasure(name)} time`, value: duration, type: 0 /* time */ }); }); disable(); enable(); @@ -134366,13 +134319,12 @@ function reportStatistics(sys2, program, solutionPerformance) { reportCountStatistic("Strict subtype cache size", caches.strictSubtype); if (isPerformanceEnabled) { forEachMeasure((name, duration) => { - if (!isSolutionMarkOrMeasure(name)) - reportTimeStatistic( - `${name} time`, - duration, - /*aggregate*/ - true - ); + if (!isSolutionMarkOrMeasure(name)) reportTimeStatistic( + `${name} time`, + duration, + /*aggregate*/ + true + ); }); } } else if (isPerformanceEnabled) { @@ -134427,12 +134379,10 @@ function reportStatistics(sys2, program, solutionPerformance) { } else { if (solutionPerformance) { forEachMeasure((name) => { - if (!isSolutionMarkOrMeasure(name)) - clearMeasures(name); + if (!isSolutionMarkOrMeasure(name)) clearMeasures(name); }); forEachMark((name) => { - if (!isSolutionMarkOrMeasure(name)) - clearMarks(name); + if (!isSolutionMarkOrMeasure(name)) clearMarks(name); }); } else { disable(); @@ -134441,8 +134391,7 @@ function reportStatistics(sys2, program, solutionPerformance) { } function reportStatisticalValue(s, aggregate) { statistics.push(s); - if (aggregate) - solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s); + if (aggregate) solutionPerformance == null ? void 0 : solutionPerformance.addAggregateStatistic(s); } function reportCountStatistic(name, count) { reportStatisticalValue( @@ -134509,8 +134458,8 @@ function createSyntacticTypeNodeBuilder(options, resolver) { serializeReturnTypeForSignature, serializeTypeOfExpression }; - function serializeExistingTypeAnnotation(type) { - return type === void 0 ? void 0 : !type.parent || !isParameter(type.parent) || !resolver.requiresAddingImplicitUndefined(type.parent) || canAddUndefined(type); + function serializeExistingTypeAnnotation(type, addUndefined) { + return type !== void 0 && (!addUndefined || type && canAddUndefined(type)) ? true : void 0; } function serializeTypeOfExpression(expr, context, addUndefined, preserveLiterals) { return typeFromExpression( @@ -134631,12 +134580,17 @@ function createSyntacticTypeNodeBuilder(options, resolver) { const declaredType = getEffectiveTypeAnnotationNode(node); const addUndefined = resolver.requiresAddingImplicitUndefined(node); let resultType; - if (!addUndefined) { - if (declaredType) { - return serializeExistingTypeAnnotation(declaredType); - } + if (declaredType) { + resultType = serializeExistingTypeAnnotation(declaredType, addUndefined); + } else { if (node.initializer && isIdentifier(node.name)) { - resultType = typeFromExpression(node.initializer, context); + resultType = typeFromExpression( + node.initializer, + context, + /*isConstContext*/ + void 0, + addUndefined + ); } } return resultType ?? inferTypeOfDeclaration(node, context); @@ -134805,7 +134759,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { expression, /*includeBigInt*/ false - ) && !isEntityNameExpression(expression)) { + )) { context.tracker.reportInferenceFallback(prop.name); result = false; } @@ -134814,27 +134768,11 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return result; } function typeFromObjectLiteral(objectLiteral, context, isConstContext) { - if (!canGetTypeFromObjectLiteral(objectLiteral, context)) - return false; + if (!canGetTypeFromObjectLiteral(objectLiteral, context)) return false; let canInferObjectLiteral = true; for (const prop of objectLiteral.properties) { Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop)); const name = prop.name; - if (prop.name.kind === 167 /* ComputedPropertyName */) { - if (!resolver.isNonNarrowedBindableName(prop.name)) { - context.tracker.reportInferenceFallback(prop.name); - } else if (isEntityNameExpression(prop.name.expression)) { - const visibilityResult = resolver.isEntityNameVisible( - prop.name.expression, - context.enclosingDeclaration, - /*shouldComputeAliasToMakeVisible*/ - false - ); - if (visibilityResult.accessibility !== 0 /* Accessible */) { - context.tracker.reportInferenceFallback(prop.name); - } - } - } switch (prop.kind) { case 174 /* MethodDeclaration */: canInferObjectLiteral = !!typeFromObjectLiteralMethod(prop, name, context) && canInferObjectLiteral; @@ -134889,8 +134827,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return true; } function canAddUndefined(node) { - if (!strictNullChecks) - return true; + if (!strictNullChecks) return true; if (isKeyword(node.kind) || node.kind === 201 /* LiteralType */ || node.kind === 184 /* FunctionType */ || node.kind === 185 /* ConstructorType */ || node.kind === 188 /* ArrayType */ || node.kind === 189 /* TupleType */ || node.kind === 187 /* TypeLiteral */ || node.kind === 203 /* TemplateLiteralType */ || node.kind === 197 /* ThisType */) { return true; } @@ -134916,6 +134853,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { function typeFromSingleReturnExpression(declaration, context) { let candidateExpr; if (declaration && !nodeIsMissing(declaration.body)) { + if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; const body = declaration.body; if (body && isBlock(body)) { forEachReturnStatement(body, (s) => { @@ -135075,8 +135013,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } }); const filesToWatch = []; - if (typeAcquisition.include) - addInferredTypings(typeAcquisition.include, "Explicitly included types"); + if (typeAcquisition.include) addInferredTypings(typeAcquisition.include, "Explicitly included types"); const exclude = typeAcquisition.exclude || []; if (!compilerOptions.types) { const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath)); @@ -135099,8 +135036,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } for (const excludeTypingName of exclude) { const didDelete = inferredTypings.delete(excludeTypingName); - if (didDelete && log) - log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`); + if (didDelete && log) log(`Typing for ${excludeTypingName} is in exclude list, will be ignored.`); } packageNameToTypingLocation.forEach((typing, name) => { const registryEntry = typesRegistry.get(name); @@ -135118,8 +135054,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } }); const result = { cachedTypingPaths, newTypingNames, filesToWatch }; - if (log) - log(`Finished typings discovery:${stringifyIndented(result)}`); + if (log) log(`Finished typings discovery:${stringifyIndented(result)}`); return result; function addInferredTyping(typingName) { if (!inferredTypings.has(typingName)) { @@ -135127,8 +135062,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } } function addInferredTypings(typingNames, message) { - if (log) - log(`${message}: ${JSON.stringify(typingNames)}`); + if (log) log(`${message}: ${JSON.stringify(typingNames)}`); forEach(typingNames, addInferredTyping); } function getTypingNames(projectRootPath2, manifestName, modulesDirName, filesToWatch2) { @@ -135165,8 +135099,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag return isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 4]) === modulesDirName || // `node_modules/@foo/bar` !isScoped && toFileNameLowerCase(pathComponents2[pathComponents2.length - 3]) === modulesDirName; }); - if (log) - log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`); + if (log) log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`); for (const manifestPath2 of dependencyManifestNames) { const normalizedFileName = normalizePath(manifestPath2); const result2 = readConfigFile(normalizedFileName, (path) => host.readFile(path)); @@ -135178,12 +135111,10 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag if (ownTypes) { const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName)); if (host.fileExists(absolutePath)) { - if (log) - log(` Package '${manifest2.name}' provides its own types.`); + if (log) log(` Package '${manifest2.name}' provides its own types.`); inferredTypings.set(manifest2.name, absolutePath); } else { - if (log) - log(` Package '${manifest2.name}' provides its own types but they are missing.`); + if (log) log(` Package '${manifest2.name}' provides its own types but they are missing.`); } } else { packageNames.push(manifest2.name); @@ -135193,8 +135124,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } function getTypingNamesFromSourceFileNames(fileNames2) { const fromFileNames = mapDefined(fileNames2, (j) => { - if (!hasJSFileExtension(j)) - return void 0; + if (!hasJSFileExtension(j)) return void 0; const inferredTypingName = removeFileExtension(toFileNameLowerCase(getBaseFileName(j))); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); return safeList.get(cleanedTypingName); @@ -135204,8 +135134,7 @@ function discoverTypings(host, log, fileNames, projectRootPath, safeList, packag } const hasJsxFile = some(fileNames2, (f) => fileExtensionIs(f, ".jsx" /* Jsx */)); if (hasJsxFile) { - if (log) - log(`Inferred 'react' typings due to presence of '.jsx' extension`); + if (log) log(`Inferred 'react' typings due to presence of '.jsx' extension`); addInferredTyping("react"); } } @@ -135356,12 +135285,12 @@ var CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind2) => { CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; return CompletionTriggerKind2; })(CompletionTriggerKind || {}); -var InlayHintKind = /* @__PURE__ */ ((InlayHintKind2) => { - InlayHintKind2["Type"] = "Type"; - InlayHintKind2["Parameter"] = "Parameter"; - InlayHintKind2["Enum"] = "Enum"; - return InlayHintKind2; -})(InlayHintKind || {}); +var InlayHintKind2 = /* @__PURE__ */ ((InlayHintKind3) => { + InlayHintKind3["Type"] = "Type"; + InlayHintKind3["Parameter"] = "Parameter"; + InlayHintKind3["Enum"] = "Enum"; + return InlayHintKind3; +})(InlayHintKind2 || {}); var HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => { HighlightSpanKind2["none"] = "none"; HighlightSpanKind2["definition"] = "definition"; @@ -135612,13 +135541,13 @@ var scanner = createScanner( /*skipTrivia*/ true ); -var SemanticMeaning = /* @__PURE__ */ ((SemanticMeaning3) => { - SemanticMeaning3[SemanticMeaning3["None"] = 0] = "None"; - SemanticMeaning3[SemanticMeaning3["Value"] = 1] = "Value"; - SemanticMeaning3[SemanticMeaning3["Type"] = 2] = "Type"; - SemanticMeaning3[SemanticMeaning3["Namespace"] = 4] = "Namespace"; - SemanticMeaning3[SemanticMeaning3["All"] = 7] = "All"; - return SemanticMeaning3; +var SemanticMeaning = /* @__PURE__ */ ((SemanticMeaning2) => { + SemanticMeaning2[SemanticMeaning2["None"] = 0] = "None"; + SemanticMeaning2[SemanticMeaning2["Value"] = 1] = "Value"; + SemanticMeaning2[SemanticMeaning2["Type"] = 2] = "Type"; + SemanticMeaning2[SemanticMeaning2["Namespace"] = 4] = "Namespace"; + SemanticMeaning2[SemanticMeaning2["All"] = 7] = "All"; + return SemanticMeaning2; })(SemanticMeaning || {}); function getMeaningFromDeclaration(node) { switch (node.kind) { @@ -136201,13 +136130,11 @@ function getAdjustedLocationForClass(node) { } if (isClassDeclaration(node)) { const defaultModifier = node.modifiers && find(node.modifiers, isDefaultModifier2); - if (defaultModifier) - return defaultModifier; + if (defaultModifier) return defaultModifier; } if (isClassExpression(node)) { const classKeyword = find(node.getChildren(), isClassKeyword); - if (classKeyword) - return classKeyword; + if (classKeyword) return classKeyword; } } function getAdjustedLocationForFunction(node) { @@ -136216,13 +136143,11 @@ function getAdjustedLocationForFunction(node) { } if (isFunctionDeclaration(node)) { const defaultModifier = find(node.modifiers, isDefaultModifier2); - if (defaultModifier) - return defaultModifier; + if (defaultModifier) return defaultModifier; } if (isFunctionExpression(node)) { const functionKeyword = find(node.getChildren(), isFunctionKeyword); - if (functionKeyword) - return functionKeyword; + if (functionKeyword) return functionKeyword; } } function getAncestorTypeNode(node) { @@ -136236,11 +136161,9 @@ function getAncestorTypeNode(node) { return lastTypeNode; } function getContextualTypeFromParentOrAncestorTypeNode(node, checker) { - if (node.flags & (16777216 /* JSDoc */ & ~524288 /* JavaScriptFile */)) - return void 0; + if (node.flags & (16777216 /* JSDoc */ & ~524288 /* JavaScriptFile */)) return void 0; const contextualType = getContextualTypeFromParent(node, checker); - if (contextualType) - return contextualType; + if (contextualType) return contextualType; const ancestorTypeNode = getAncestorTypeNode(node); return ancestorTypeNode && checker.getTypeAtLocation(ancestorTypeNode); } @@ -136519,8 +136442,7 @@ function findFirstNonJsxWhitespaceToken(sourceFile, position) { let tokenAtPosition = getTokenAtPosition(sourceFile, position); while (isWhiteSpaceOnlyJsxText(tokenAtPosition)) { const nextToken = findNextToken(tokenAtPosition, tokenAtPosition.parent, sourceFile); - if (!nextToken) - return; + if (!nextToken) return; tokenAtPosition = nextToken; } return tokenAtPosition; @@ -136700,8 +136622,7 @@ function isInsideJsxElement(sourceFile, position) { if (node.kind >= 285 /* JsxSelfClosingElement */ && node.kind <= 294 /* JsxExpression */ || node.kind === 12 /* JsxText */ || node.kind === 30 /* LessThanToken */ || node.kind === 32 /* GreaterThanToken */ || node.kind === 80 /* Identifier */ || node.kind === 20 /* CloseBraceToken */ || node.kind === 19 /* OpenBraceToken */ || node.kind === 44 /* SlashToken */) { node = node.parent; } else if (node.kind === 284 /* JsxElement */) { - if (position > node.getStart(sourceFile)) - return true; + if (position > node.getStart(sourceFile)) return true; node = node.parent; } else { return false; @@ -136777,8 +136698,7 @@ function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { if (token && token.kind === 29 /* QuestionDotToken */) { token = findPrecedingToken(token.getFullStart(), sourceFile); } - if (!token || !isIdentifier(token)) - return void 0; + if (!token || !isIdentifier(token)) return void 0; if (!remainingLessThanTokens) { return isDeclarationName(token) ? void 0 : { called: token, nTypeArguments }; } @@ -136795,18 +136715,15 @@ function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { break; case 20 /* CloseBraceToken */: token = findPrecedingMatchingToken(token, 19 /* OpenBraceToken */, sourceFile); - if (!token) - return void 0; + if (!token) return void 0; break; case 22 /* CloseParenToken */: token = findPrecedingMatchingToken(token, 21 /* OpenParenToken */, sourceFile); - if (!token) - return void 0; + if (!token) return void 0; break; case 24 /* CloseBracketToken */: token = findPrecedingMatchingToken(token, 23 /* OpenBracketToken */, sourceFile); - if (!token) - return void 0; + if (!token) return void 0; break; case 28 /* CommaToken */: nTypeArguments++; @@ -136855,24 +136772,15 @@ function nodeHasTokens(n, sourceFile) { function getNodeModifiers(node, excludeFlags = 0 /* None */) { const result = []; const flags = isDeclaration(node) ? getCombinedNodeFlagsAlwaysIncludeJSDoc(node) & ~excludeFlags : 0 /* None */; - if (flags & 2 /* Private */) - result.push("private" /* privateMemberModifier */); - if (flags & 4 /* Protected */) - result.push("protected" /* protectedMemberModifier */); - if (flags & 1 /* Public */) - result.push("public" /* publicMemberModifier */); - if (flags & 256 /* Static */ || isClassStaticBlockDeclaration(node)) - result.push("static" /* staticModifier */); - if (flags & 64 /* Abstract */) - result.push("abstract" /* abstractModifier */); - if (flags & 32 /* Export */) - result.push("export" /* exportedModifier */); - if (flags & 65536 /* Deprecated */) - result.push("deprecated" /* deprecatedModifier */); - if (node.flags & 33554432 /* Ambient */) - result.push("declare" /* ambientModifier */); - if (node.kind === 277 /* ExportAssignment */) - result.push("export" /* exportedModifier */); + if (flags & 2 /* Private */) result.push("private" /* privateMemberModifier */); + if (flags & 4 /* Protected */) result.push("protected" /* protectedMemberModifier */); + if (flags & 1 /* Public */) result.push("public" /* publicMemberModifier */); + if (flags & 256 /* Static */ || isClassStaticBlockDeclaration(node)) result.push("static" /* staticModifier */); + if (flags & 64 /* Abstract */) result.push("abstract" /* abstractModifier */); + if (flags & 32 /* Export */) result.push("export" /* exportedModifier */); + if (flags & 65536 /* Deprecated */) result.push("deprecated" /* deprecatedModifier */); + if (node.flags & 33554432 /* Ambient */) result.push("declare" /* ambientModifier */); + if (node.kind === 277 /* ExportAssignment */) result.push("export" /* exportedModifier */); return result.length > 0 ? result.join(",") : "" /* none */; } function getTypeArgumentOrTypeParameterList(node) { @@ -136960,8 +136868,7 @@ function isInReferenceCommentWorker(sourceFile, position, shouldBeReference) { return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } function getReplacementSpanForContextToken(contextToken) { - if (!contextToken) - return void 0; + if (!contextToken) return void 0; switch (contextToken.kind) { case 11 /* StringLiteral */: case 15 /* NoSubstitutionTemplateLiteral */: @@ -136976,8 +136883,7 @@ function createTextSpanFromNode(node, sourceFile, endNode2) { function createTextSpanFromStringLiteralLikeContent(node) { let replacementEnd = node.getEnd() - 1; if (node.isUnterminated) { - if (node.getStart() === replacementEnd) - return void 0; + if (node.getStart() === replacementEnd) return void 0; replacementEnd = node.getEnd(); } return createTextSpanFromBounds(node.getStart() + 1, replacementEnd); @@ -137095,9 +137001,6 @@ function getModuleSpecifierResolverHost(program, host) { function moduleResolutionUsesNodeModules(moduleResolution) { return moduleResolution === 2 /* Node10 */ || moduleResolution >= 3 /* Node16 */ && moduleResolution <= 99 /* NodeNext */ || moduleResolution === 100 /* Bundler */; } -function makeImportIfNecessary(defaultImport, namedImports, moduleSpecifier, quotePreference) { - return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : void 0; -} function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference, isTypeOnly) { return factory.createImportDeclaration( /*modifiers*/ @@ -137111,10 +137014,10 @@ function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreferenc function makeStringLiteral(text, quotePreference) { return factory.createStringLiteral(text, quotePreference === 0 /* Single */); } -var QuotePreference = /* @__PURE__ */ ((QuotePreference7) => { - QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; - QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; - return QuotePreference7; +var QuotePreference = /* @__PURE__ */ ((QuotePreference6) => { + QuotePreference6[QuotePreference6["Single"] = 0] = "Single"; + QuotePreference6[QuotePreference6["Double"] = 1] = "Double"; + return QuotePreference6; })(QuotePreference || {}); function quotePreferenceFromString(str, sourceFile) { return isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; @@ -137165,8 +137068,7 @@ function getPropertySymbolFromBindingElement(checker, bindingElement) { return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } function getParentNodeInSpan(node, file, span) { - if (!node) - return void 0; + if (!node) return void 0; while (node.parent) { if (isSourceFile(node.parent) || !spanContainsNode(span, node.parent, file)) { return node; @@ -137266,8 +137168,7 @@ function getMappedLocation(location, sourceMapper, fileExists) { function getMappedDocumentSpan(documentSpan, sourceMapper, fileExists) { const { fileName, textSpan } = documentSpan; const newPosition = getMappedLocation({ fileName, pos: textSpan.start }, sourceMapper, fileExists); - if (!newPosition) - return void 0; + if (!newPosition) return void 0; const newEndPosition = getMappedLocation({ fileName, pos: textSpan.start + textSpan.length }, sourceMapper, fileExists); const newLength = newEndPosition ? newEndPosition.pos - newPosition.pos : textSpan.length; return { @@ -137350,8 +137251,7 @@ function getDisplayPartWriter() { clear: resetWriter }; function writeIndent() { - if (length2 > absoluteMaximumLength) - return; + if (length2 > absoluteMaximumLength) return; if (lineStart) { const indentString = getIndentString(indent3); if (indentString) { @@ -137362,22 +137262,19 @@ function getDisplayPartWriter() { } } function writeKind(text, kind) { - if (length2 > absoluteMaximumLength) - return; + if (length2 > absoluteMaximumLength) return; writeIndent(); length2 += text.length; displayParts.push(displayPart(text, kind)); } function writeSymbol(text, symbol) { - if (length2 > absoluteMaximumLength) - return; + if (length2 > absoluteMaximumLength) return; writeIndent(); length2 += text.length; displayParts.push(symbolPart(text, symbol)); } function writeLine() { - if (length2 > absoluteMaximumLength) - return; + if (length2 > absoluteMaximumLength) return; length2 += 1; displayParts.push(lineBreakPart()); lineStart = true; @@ -137396,32 +137293,19 @@ function symbolPart(text, symbol) { if (flags & 3 /* Variable */) { return isFirstDeclarationOfSymbolParameter(symbol2) ? 13 /* parameterName */ : 9 /* localName */; } - if (flags & 4 /* Property */) - return 14 /* propertyName */; - if (flags & 32768 /* GetAccessor */) - return 14 /* propertyName */; - if (flags & 65536 /* SetAccessor */) - return 14 /* propertyName */; - if (flags & 8 /* EnumMember */) - return 19 /* enumMemberName */; - if (flags & 16 /* Function */) - return 20 /* functionName */; - if (flags & 32 /* Class */) - return 1 /* className */; - if (flags & 64 /* Interface */) - return 4 /* interfaceName */; - if (flags & 384 /* Enum */) - return 2 /* enumName */; - if (flags & 1536 /* Module */) - return 11 /* moduleName */; - if (flags & 8192 /* Method */) - return 10 /* methodName */; - if (flags & 262144 /* TypeParameter */) - return 18 /* typeParameterName */; - if (flags & 524288 /* TypeAlias */) - return 0 /* aliasName */; - if (flags & 2097152 /* Alias */) - return 0 /* aliasName */; + if (flags & 4 /* Property */) return 14 /* propertyName */; + if (flags & 32768 /* GetAccessor */) return 14 /* propertyName */; + if (flags & 65536 /* SetAccessor */) return 14 /* propertyName */; + if (flags & 8 /* EnumMember */) return 19 /* enumMemberName */; + if (flags & 16 /* Function */) return 20 /* functionName */; + if (flags & 32 /* Class */) return 1 /* className */; + if (flags & 64 /* Interface */) return 4 /* interfaceName */; + if (flags & 384 /* Enum */) return 2 /* enumName */; + if (flags & 1536 /* Module */) return 11 /* moduleName */; + if (flags & 8192 /* Method */) return 10 /* methodName */; + if (flags & 262144 /* TypeParameter */) return 18 /* typeParameterName */; + if (flags & 524288 /* TypeAlias */) return 0 /* aliasName */; + if (flags & 2097152 /* Alias */) return 0 /* aliasName */; return 17 /* text */; } } @@ -137492,8 +137376,7 @@ function buildLinkParts(link, checker) { const decl = (targetSymbol == null ? void 0 : targetSymbol.valueDeclaration) || ((_a = targetSymbol == null ? void 0 : targetSymbol.declarations) == null ? void 0 : _a[0]); if (decl) { parts.push(linkNamePart(name, decl)); - if (text) - parts.push(linkTextPart(text)); + if (text) parts.push(linkTextPart(text)); } else { const separator = suffix === 0 || link.text.charCodeAt(suffix) === 124 /* bar */ && name.charCodeAt(name.length - 1) !== 32 /* space */ ? " " : ""; parts.push(linkTextPart(name + separator + text)); @@ -137505,8 +137388,7 @@ function buildLinkParts(link, checker) { function skipSeparatorFromLinkText(text) { let pos = 0; if (text.charCodeAt(pos++) === 124 /* bar */) { - while (pos < text.length && text.charCodeAt(pos) === 32 /* space */) - pos++; + while (pos < text.length && text.charCodeAt(pos) === 32 /* space */) pos++; return text.slice(pos); } return text; @@ -137514,23 +137396,18 @@ function skipSeparatorFromLinkText(text) { function findLinkNameEnd(text) { let pos = text.indexOf("://"); if (pos === 0) { - while (pos < text.length && text.charCodeAt(pos) !== 124 /* bar */) - pos++; + while (pos < text.length && text.charCodeAt(pos) !== 124 /* bar */) pos++; return pos; } - if (text.indexOf("()") === 0) - return 2; + if (text.indexOf("()") === 0) return 2; if (text.charAt(0) === "<") { let brackets2 = 0; let i = 0; while (i < text.length) { - if (text[i] === "<") - brackets2++; - if (text[i] === ">") - brackets2--; + if (text[i] === "<") brackets2++; + if (text[i] === ">") brackets2--; i++; - if (!brackets2) - return i; + if (!brackets2) return i; } } return 0; @@ -137618,9 +137495,12 @@ function getPrecedingNonSpaceCharacterPosition(text, position) { } function getSynthesizedDeepClone(node, includeTrivia = true) { const clone2 = node && getSynthesizedDeepCloneWorker(node); - if (clone2 && !includeTrivia) - suppressLeadingAndTrailingTrivia(clone2); - return clone2; + if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2); + return setParentRecursive( + clone2, + /*incremental*/ + false + ); } function getSynthesizedDeepCloneWithReplacements(node, includeTrivia, replaceNode) { let clone2 = replaceNode(node); @@ -137629,8 +137509,7 @@ function getSynthesizedDeepCloneWithReplacements(node, includeTrivia, replaceNod } else { clone2 = getSynthesizedDeepCloneWorker(node, replaceNode); } - if (clone2 && !includeTrivia) - suppressLeadingAndTrailingTrivia(clone2); + if (clone2 && !includeTrivia) suppressLeadingAndTrailingTrivia(clone2); return clone2; } function getSynthesizedDeepCloneWorker(node, replaceNode) { @@ -137696,16 +137575,14 @@ function hasLeadingLineBreak(node, text) { const start = node.getFullStart(); const end = node.getStart(); for (let i = start; i < end; i++) { - if (text.charCodeAt(i) === 10 /* lineFeed */) - return true; + if (text.charCodeAt(i) === 10 /* lineFeed */) return true; } return false; } function addEmitFlagsRecursively(node, flag, getChild) { addEmitFlags(node, flag); const child = getChild(node); - if (child) - addEmitFlagsRecursively(child, flag, getChild); + if (child) addEmitFlagsRecursively(child, flag, getChild); } function getFirstChild(node) { return node.forEachChild((child) => child); @@ -137759,13 +137636,10 @@ function getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailing }; } function indexInTextChange(change, name) { - if (startsWith(change, name)) - return 0; + if (startsWith(change, name)) return 0; let idx = change.indexOf(" " + name); - if (idx === -1) - idx = change.indexOf("." + name); - if (idx === -1) - idx = change.indexOf('"' + name); + if (idx === -1) idx = change.indexOf("." + name); + if (idx === -1) idx = change.indexOf('"' + name); return idx === -1 ? -1 : idx + 1; } function needsParentheses(expression) { @@ -137975,8 +137849,7 @@ function findPackageJsons(startDirectory, host, stopDirectory) { function findPackageJson(directory, host) { let packageJson; forEachAncestorDirectory(directory, (ancestor) => { - if (ancestor === "node_modules") - return true; + if (ancestor === "node_modules") return true; packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); if (packageJson) { return true; @@ -138223,29 +138096,27 @@ function firstOrOnly(valueOrArray) { function getNamesForExportedSymbol(symbol, scriptTarget) { if (needsNameFromDeclaration(symbol)) { const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); - if (fromDeclaration) - return fromDeclaration; - const fileNameCase = ts_codefix_exports.moduleSymbolToValidIdentifier( + if (fromDeclaration) return fromDeclaration; + const fileNameCase = moduleSymbolToValidIdentifier( getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ false ); - const capitalized = ts_codefix_exports.moduleSymbolToValidIdentifier( + const capitalized = moduleSymbolToValidIdentifier( getSymbolParentOrFail(symbol), scriptTarget, /*forceCapitalize*/ true ); - if (fileNameCase === capitalized) - return fileNameCase; + if (fileNameCase === capitalized) return fileNameCase; return [fileNameCase, capitalized]; } return symbol.name; } function getNameForExportedSymbol(symbol, scriptTarget, preferCapitalized) { if (needsNameFromDeclaration(symbol)) { - return getDefaultLikeExportNameFromDeclaration(symbol) || ts_codefix_exports.moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized); + return getDefaultLikeExportNameFromDeclaration(symbol) || moduleSymbolToValidIdentifier(getSymbolParentOrFail(symbol), scriptTarget, !!preferCapitalized); } return symbol.name; } @@ -138276,14 +138147,43 @@ function getSymbolParentOrFail(symbol) { }).join(", ")}.` ); } +function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { + return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize); +} +function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { + const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index")); + let res = ""; + let lastCharWasValid = true; + const firstCharCode = baseName.charCodeAt(0); + if (isIdentifierStart(firstCharCode, target)) { + res += String.fromCharCode(firstCharCode); + if (forceCapitalize) { + res = res.toUpperCase(); + } + } else { + lastCharWasValid = false; + } + for (let i = 1; i < baseName.length; i++) { + const ch = baseName.charCodeAt(i); + const isValid = isIdentifierPart(ch, target); + if (isValid) { + let char = String.fromCharCode(ch); + if (!lastCharWasValid) { + char = char.toUpperCase(); + } + res += char; + } + lastCharWasValid = isValid; + } + return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; +} function stringContainsAt(haystack, needle, startIndex) { const needleLength = needle.length; if (needleLength + startIndex > haystack.length) { return false; } for (let i = 0; i < needleLength; i++) { - if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) - return false; + if (needle.charCodeAt(i) !== haystack.charCodeAt(i + startIndex)) return false; } return true; } @@ -138523,8 +138423,7 @@ function createCacheableExportInfoMap(host) { const target = skipAlias(symbol, checker); const storedSymbol = symbol.flags & 33554432 /* Transient */ ? void 0 : symbol; const storedModuleSymbol = moduleSymbol.flags & 33554432 /* Transient */ ? void 0 : moduleSymbol; - if (!storedSymbol || !storedModuleSymbol) - symbols.set(id, [symbol, moduleSymbol]); + if (!storedSymbol || !storedModuleSymbol) symbols.set(id, [symbol, moduleSymbol]); exportInfo.add(key(symbolName2, symbol, isExternalModuleNameRelative(moduleName) ? void 0 : moduleName, checker), { id, symbolTableKey, @@ -138542,14 +138441,12 @@ function createCacheableExportInfoMap(host) { }); }, get: (importingFile, key2) => { - if (importingFile !== usableByFileName) - return; + if (importingFile !== usableByFileName) return; const result = exportInfo.get(key2); return result == null ? void 0 : result.map(rehydrateCachedInfo); }, search: (importingFile, preferCapitalized, matches, action) => { - if (importingFile !== usableByFileName) - return; + if (importingFile !== usableByFileName) return; return forEachEntry(exportInfo, (info, key2) => { const { symbolName: symbolName2, ambientModuleName } = parseKey(key2); const name = preferCapitalized && info[0].capitalizedSymbolName || symbolName2; @@ -138558,8 +138455,7 @@ function createCacheableExportInfoMap(host) { const filtered = rehydrated.filter((r, i) => isNotShadowedByDeeperNodeModulesPackage(r, info[i].packageName)); if (filtered.length) { const res = action(filtered, name, !!ambientModuleName, key2); - if (res !== void 0) - return res; + if (res !== void 0) return res; } } }); @@ -138589,8 +138485,7 @@ function createCacheableExportInfoMap(host) { } return cache; function rehydrateCachedInfo(info) { - if (info.symbol && info.moduleSymbol) - return info; + if (info.symbol && info.moduleSymbol) return info; const { id, exportKind, targetFlags, isFromPackageJson, moduleFileName } = info; const [cachedSymbol, cachedModuleSymbol] = symbols.get(id) || emptyArray; if (cachedSymbol && cachedModuleSymbol) { @@ -138655,19 +138550,16 @@ function createCacheableExportInfoMap(host) { return true; } function isNotShadowedByDeeperNodeModulesPackage(info, packageName) { - if (!packageName || !info.moduleFileName) - return true; + if (!packageName || !info.moduleFileName) return true; const typingsCacheLocation = host.getGlobalTypingsCacheLocation(); - if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) - return true; + if (typingsCacheLocation && startsWith(info.moduleFileName, typingsCacheLocation)) return true; const packageDeepestNodeModulesPath = packages.get(packageName); return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath); } } function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { var _a; - if (from === to) - return false; + if (from === to) return false; const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(from.path, to.path, preferences, {}); if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) { return !cachedResult.isBlockedByPackageJsonDependencies; @@ -138740,8 +138632,7 @@ function forEachExternalModule(checker, allSourceFiles, excludePatterns, host, c var _a, _b; const realpathsWithSymlinks = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); const isExcluded = excludePatterns && (({ fileName, path }) => { - if (excludePatterns.some((p) => p.test(fileName))) - return true; + if (excludePatterns.some((p) => p.test(fileName))) return true; if ((realpathsWithSymlinks == null ? void 0 : realpathsWithSymlinks.size) && pathContainsNodeModules(fileName)) { let dir = getDirectoryPath(fileName); return forEachAncestorDirectory(getDirectoryPath(path), (dirPath) => { @@ -138789,7 +138680,6 @@ function getExportInfoMap(importingFile, host, program, preferences, cancellatio return cache; } (_d = host.log) == null ? void 0 : _d.call(host, "getExportInfoMap: cache miss or empty; calculating new results"); - const compilerOptions = program.getCompilerOptions(); let moduleCount = 0; try { forEachExternalModuleToImportFrom( @@ -138799,11 +138689,10 @@ function getExportInfoMap(importingFile, host, program, preferences, cancellatio /*useAutoImportProvider*/ true, (moduleSymbol, moduleFile, program2, isFromPackageJson) => { - if (++moduleCount % 100 === 0) - cancellationToken == null ? void 0 : cancellationToken.throwIfCancellationRequested(); + if (++moduleCount % 100 === 0) cancellationToken == null ? void 0 : cancellationToken.throwIfCancellationRequested(); const seenExports = /* @__PURE__ */ new Map(); const checker = program2.getTypeChecker(); - const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker); if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { cache.add( importingFile.path, @@ -138839,53 +138728,37 @@ function getExportInfoMap(importingFile, host, program, preferences, cancellatio (_e = host.log) == null ? void 0 : _e.call(host, `getExportInfoMap: done in ${timestamp() - start} ms`); return cache; } -function getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions) { - const exported = getDefaultLikeExportWorker(moduleSymbol, checker); - if (!exported) - return void 0; - const { symbol, exportKind } = exported; - const info = getDefaultExportInfoWorker(symbol, checker, compilerOptions); - return info && { symbol, exportKind, ...info }; +function getDefaultLikeExportInfo(moduleSymbol, checker) { + const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); + if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; + const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); + if (defaultExport) return { symbol: defaultExport, exportKind: 1 /* Default */ }; } function isImportableSymbol(symbol, checker) { return !checker.isUndefinedSymbol(symbol) && !checker.isUnknownSymbol(symbol) && !isKnownSymbol(symbol) && !isPrivateIdentifierSymbol(symbol); } -function getDefaultLikeExportWorker(moduleSymbol, checker) { - const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) - return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; - const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); - if (defaultExport) - return { symbol: defaultExport, exportKind: 1 /* Default */ }; -} -function getDefaultExportInfoWorker(defaultExport, checker, compilerOptions) { - const localSymbol = getLocalSymbolForExportDefault(defaultExport); - if (localSymbol) - return { resolvedSymbol: localSymbol, name: localSymbol.name }; - const name = getNameForExportDefault(defaultExport); - if (name !== void 0) - return { resolvedSymbol: defaultExport, name }; - if (defaultExport.flags & 2097152 /* Alias */) { - const aliased = checker.getImmediateAliasedSymbol(defaultExport); - if (aliased && aliased.parent) { - return getDefaultExportInfoWorker(aliased, checker, compilerOptions); +function forEachNameOfDefaultExport(defaultExport, checker, compilerOptions, preferCapitalizedNames, cb) { + let chain; + let current = defaultExport; + while (current) { + const fromDeclaration = getDefaultLikeExportNameFromDeclaration(current); + if (fromDeclaration) { + const final = cb(fromDeclaration); + if (final) return final; } + if (current.escapedName !== "default" /* Default */ && current.escapedName !== "export=" /* ExportEquals */) { + const final = cb(current.name); + if (final) return final; + } + chain = append(chain, current); + current = current.flags & 2097152 /* Alias */ ? checker.getImmediateAliasedSymbol(current) : void 0; } - if (defaultExport.escapedName !== "default" /* Default */ && defaultExport.escapedName !== "export=" /* ExportEquals */) { - return { resolvedSymbol: defaultExport, name: defaultExport.getName() }; - } - return { resolvedSymbol: defaultExport, name: getNameForExportedSymbol(defaultExport, compilerOptions.target) }; -} -function getNameForExportDefault(symbol) { - return symbol.declarations && firstDefined(symbol.declarations, (declaration) => { - var _a; - if (isExportAssignment(declaration)) { - return (_a = tryCast(skipOuterExpressions(declaration.expression), isIdentifier)) == null ? void 0 : _a.text; - } else if (isExportSpecifier(declaration)) { - Debug.assert(declaration.name.text === "default" /* Default */, "Expected the specifier to be a default export"); - return declaration.propertyName && declaration.propertyName.text; + for (const symbol of chain ?? emptyArray) { + if (symbol.parent && isExternalModuleSymbol(symbol.parent)) { + const final = cb(moduleSymbolToValidIdentifier(symbol.parent, getEmitScriptTarget(compilerOptions), preferCapitalizedNames)); + if (final) return final; } - }); + } } // src/services/classifier.ts @@ -139018,16 +138891,14 @@ var noRegexTable = arrayToNumericMap( function getNewEndOfLineState(scanner2, token, lastOnTemplateStack) { switch (token) { case 11 /* StringLiteral */: { - if (!scanner2.isUnterminated()) - return void 0; + if (!scanner2.isUnterminated()) return void 0; const tokenText = scanner2.getTokenText(); const lastCharIndex = tokenText.length - 1; let numBackslashes = 0; while (tokenText.charCodeAt(lastCharIndex - numBackslashes) === 92 /* backslash */) { numBackslashes++; } - if ((numBackslashes & 1) === 0) - return void 0; + if ((numBackslashes & 1) === 0) return void 0; return tokenText.charCodeAt(0) === 34 /* doubleQuote */ ? 3 /* InDoubleQuoteStringLiteral */ : 2 /* InSingleQuoteStringLiteral */; } case 3 /* MultiLineCommentTrivia */: @@ -139804,8 +139675,7 @@ var DocumentHighlights; void 0, sourceFilesSet ); - if (!referenceEntries) - return void 0; + if (!referenceEntries) return void 0; const map2 = arrayToMultiMap(referenceEntries.map(ts_FindAllReferences_exports.toHighlightSpan), (e) => e.fileName, (e) => e.span); const getCanonicalFileName = createGetCanonicalFileName(program.useCaseSensitiveFileNames()); return arrayFrom(mapDefinedIterator(map2.entries(), ([fileName, highlightSpans]) => { @@ -140406,8 +140276,7 @@ function getPathUpdater(oldFileOrDirPath, newFileOrDirPath, getCanonicalFileName return originalPath ? updatedPath === void 0 ? void 0 : makeCorrespondingRelativeChange(originalPath.fileName, updatedPath, path, getCanonicalFileName) : updatedPath; }; function getUpdatedPath(pathToUpdate) { - if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) - return newFileOrDirPath; + if (getCanonicalFileName(pathToUpdate) === canonicalOldPath) return newFileOrDirPath; const suffix = tryRemoveDirectoryPrefix(pathToUpdate, canonicalOldPath, getCanonicalFileName); return suffix === void 0 ? void 0 : newFileOrDirPath + "/" + suffix; } @@ -140418,23 +140287,19 @@ function makeCorrespondingRelativeChange(a0, b0, a1, getCanonicalFileName) { } function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, newFileOrDirPath, currentDirectory, useCaseSensitiveFileNames2) { const { configFile } = program.getCompilerOptions(); - if (!configFile) - return; + if (!configFile) return; const configDir = getDirectoryPath(configFile.fileName); const jsonObjectLiteral = getTsConfigObjectLiteralExpression(configFile); - if (!jsonObjectLiteral) - return; + if (!jsonObjectLiteral) return; forEachProperty(jsonObjectLiteral, (property, propertyName) => { switch (propertyName) { case "files": case "include": case "exclude": { const foundExactMatch = updatePaths(property); - if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) - return; + if (foundExactMatch || propertyName !== "include" || !isArrayLiteralExpression(property.initializer)) return; const includes = mapDefined(property.initializer.elements, (e) => isStringLiteral(e) ? e.text : void 0); - if (includes.length === 0) - return; + if (includes.length === 0) return; const matchers = getFileMatcherPatterns( configDir, /*excludes*/ @@ -140456,8 +140321,7 @@ function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, updatePaths(property2); } else if (propertyName2 === "paths") { forEachProperty(property2.initializer, (pathsProperty) => { - if (!isArrayLiteralExpression(pathsProperty.initializer)) - return; + if (!isArrayLiteralExpression(pathsProperty.initializer)) return; for (const e of pathsProperty.initializer.elements) { tryUpdateString(e); } @@ -140476,8 +140340,7 @@ function updateTsconfigFiles(program, changeTracker, oldToNew, oldFileOrDirPath, return foundExactMatch; } function tryUpdateString(element) { - if (!isStringLiteral(element)) - return false; + if (!isStringLiteral(element)) return false; const elementFileName = combinePathsSafe(configDir, element.text); const updated = oldToNew(elementFileName); if (updated !== void 0) { @@ -140506,15 +140369,13 @@ function updateImports(program, changeTracker, oldToNew, newToOld, host, getCano const oldImportFromDirectory = getDirectoryPath(oldImportFromPath); const importingSourceFileMoved = newFromOld !== void 0 || oldFromNew !== void 0; updateImportsWorker(sourceFile, changeTracker, (referenceText) => { - if (!pathIsRelative(referenceText)) - return void 0; + if (!pathIsRelative(referenceText)) return void 0; const oldAbsolute = combinePathsSafe(oldImportFromDirectory, referenceText); const newAbsolute = oldToNew(oldAbsolute); return newAbsolute === void 0 ? void 0 : ensurePathIsNonModuleName(getRelativePathFromDirectory(newImportFromDirectory, newAbsolute, getCanonicalFileName)); }, (importLiteral) => { const importedModuleSymbol = program.getTypeChecker().getSymbolAtLocation(importLiteral); - if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d))) - return void 0; + if ((importedModuleSymbol == null ? void 0 : importedModuleSymbol.declarations) && importedModuleSymbol.declarations.some((d) => isAmbientModule(d))) return void 0; const toImport = oldFromNew !== void 0 ? getSourceFileToImportFromResolved(importLiteral, resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, allFiles) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); return toImport !== void 0 && (toImport.updated || importingSourceFileMoved && pathIsRelative(importLiteral.text)) ? ts_moduleSpecifiers_exports.updateModuleSpecifier(program.getCompilerOptions(), sourceFile, newImportFromPath, toImport.newFileName, createModuleSpecifierResolutionHost(program, host), importLiteral.text) : void 0; }); @@ -140533,21 +140394,18 @@ function getSourceFileToImport(importedModuleSymbol, importLiteral, importingSou return newFileName === void 0 ? { newFileName: oldFileName, updated: false } : { newFileName, updated: true }; } else { const mode = program.getModeForUsageLocation(importingSourceFile, importLiteral); - const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? program.getResolvedModuleFromModuleSpecifier(importLiteral) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); + const resolved = host.resolveModuleNameLiterals || !host.resolveModuleNames ? program.getResolvedModuleFromModuleSpecifier(importLiteral, importingSourceFile) : host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName, mode); return getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, program.getSourceFiles()); } } function getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, sourceFiles) { - if (!resolved) - return void 0; + if (!resolved) return void 0; if (resolved.resolvedModule) { const result2 = tryChange(resolved.resolvedModule.resolvedFileName); - if (result2) - return result2; + if (result2) return result2; } const result = forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJsonExisting) || pathIsRelative(importLiteral.text) && forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); - if (result) - return result; + if (result) return result; return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; function tryChangeWithIgnoringPackageJsonExisting(oldFileName) { const newFileName = oldToNew(oldFileName); @@ -140564,21 +140422,18 @@ function getSourceFileToImportFromResolved(importLiteral, resolved, oldToNew, so function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { for (const ref of sourceFile.referencedFiles || emptyArray) { const updated = updateRef(ref.fileName); - if (updated !== void 0 && updated !== sourceFile.text.slice(ref.pos, ref.end)) - changeTracker.replaceRangeWithText(sourceFile, ref, updated); + if (updated !== void 0 && updated !== sourceFile.text.slice(ref.pos, ref.end)) changeTracker.replaceRangeWithText(sourceFile, ref, updated); } for (const importStringLiteral of sourceFile.imports) { const updated = updateImport(importStringLiteral); - if (updated !== void 0 && updated !== importStringLiteral.text) - changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); + if (updated !== void 0 && updated !== importStringLiteral.text) changeTracker.replaceRangeWithText(sourceFile, createStringRange(importStringLiteral, sourceFile), updated); } } function createStringRange(node, sourceFile) { return createRange(node.getStart(sourceFile) + 1, node.end - 1); } function forEachProperty(objectLiteral, cb) { - if (!isObjectLiteralExpression(objectLiteral)) - return; + if (!isObjectLiteralExpression(objectLiteral)) return; for (const property of objectLiteral.properties) { if (isPropertyAssignment(property) && isStringLiteral(property.name)) { cb(property, property.name.text); @@ -140618,8 +140473,7 @@ function createPatternMatcher(pattern) { patternContainsDots: false }; } - if (dotSeparatedSegments.some((segment) => !segment.subWordTextChunks.length)) - return void 0; + if (dotSeparatedSegments.some((segment) => !segment.subWordTextChunks.length)) return void 0; return { getFullMatch: (containers, candidate) => getFullMatch(containers, candidate, dotSeparatedSegments, stringToWordSpans), getMatchForLastSegmentOfPattern: (candidate) => matchSegment(candidate, last(dotSeparatedSegments), stringToWordSpans), @@ -140657,8 +140511,7 @@ function matchTextChunk(candidate, chunk, stringToWordSpans) { ); } if (chunk.isLowerCase) { - if (index === -1) - return void 0; + if (index === -1) return void 0; const wordSpans = getWordSpans(candidate, stringToWordSpans); for (const span of wordSpans) { if (partStartsWith( @@ -140720,8 +140573,7 @@ function matchTextChunk(candidate, chunk, stringToWordSpans) { function matchSegment(candidate, segment, stringToWordSpans) { if (every2(segment.totalTextChunk.text, (ch) => ch !== 32 /* space */ && ch !== 42 /* asterisk */)) { const match = matchTextChunk(candidate, segment.totalTextChunk, stringToWordSpans); - if (match) - return match; + if (match) return match; } const subWordTextChunks = segment.subWordTextChunks; let bestMatch; @@ -141304,8 +141156,7 @@ function getSourceMapper(host) { function getDocumentPositionMapper2(generatedFileName, sourceFileName) { const path = toPath3(generatedFileName); const value = documentPositionMappers.get(path); - if (value) - return value; + if (value) return value; let mapper; if (host.getDocumentPositionMapper) { mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); @@ -141322,20 +141173,16 @@ function getSourceMapper(host) { return mapper || identitySourceMapConsumer; } function tryGetSourcePosition(info) { - if (!isDeclarationFileName(info.fileName)) - return void 0; + if (!isDeclarationFileName(info.fileName)) return void 0; const file = getSourceFile(info.fileName); - if (!file) - return void 0; + if (!file) return void 0; const newLoc = getDocumentPositionMapper2(info.fileName).getSourcePosition(info); return !newLoc || newLoc === info ? void 0 : tryGetSourcePosition(newLoc) || newLoc; } function tryGetGeneratedPosition(info) { - if (isDeclarationFileName(info.fileName)) - return void 0; + if (isDeclarationFileName(info.fileName)) return void 0; const sourceFile = getSourceFile(info.fileName); - if (!sourceFile) - return void 0; + if (!sourceFile) return void 0; const program = host.getProgram(); if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) { return void 0; @@ -141343,15 +141190,13 @@ function getSourceMapper(host) { const options = program.getCompilerOptions(); const outPath = options.outFile; const declarationPath = outPath ? removeFileExtension(outPath) + ".d.ts" /* Dts */ : getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); - if (declarationPath === void 0) - return void 0; + if (declarationPath === void 0) return void 0; const newLoc = getDocumentPositionMapper2(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? void 0 : newLoc; } function getSourceFile(fileName) { const program = host.getProgram(); - if (!program) - return void 0; + if (!program) return void 0; const path = toPath3(fileName); const file = program.getSourceFileByPath(path); return file && file.resolvedPath === path ? file : void 0; @@ -141359,8 +141204,7 @@ function getSourceMapper(host) { function getOrCreateSourceFileLike(fileName) { const path = toPath3(fileName); const fileFromCache = sourceFileLike.get(path); - if (fileFromCache !== void 0) - return fileFromCache ? fileFromCache : void 0; + if (fileFromCache !== void 0) return fileFromCache ? fileFromCache : void 0; if (!host.readFile || host.fileExists && !host.fileExists(fileName)) { sourceFileLike.set(path, false); return void 0; @@ -141417,8 +141261,7 @@ function convertDocumentToSourceMapper(host, contents, mapFileName) { if (!map2 || !map2.sources || !map2.file || !map2.mappings) { return void 0; } - if (map2.sourcesContent && map2.sourcesContent.some(isString)) - return void 0; + if (map2.sourcesContent && map2.sourcesContent.some(isString)) return void 0; return createDocumentPositionMapper(host, map2, mapFileName); } function createSourceFileLike(text, lineMap) { @@ -141449,9 +141292,8 @@ function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { for (const moduleSpecifier of sourceFile.imports) { const importNode = importFromModuleSpecifier(moduleSpecifier); const name = importNameForConvertToDefaultImport(importNode); - if (!name) - continue; - const module2 = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier)) == null ? void 0 : _a.resolvedModule; + if (!name) continue; + const module2 = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule; const resolvedFile = module2 && program.getSourceFile(module2.resolvedFileName); if (resolvedFile && resolvedFile.externalModuleIndicator && resolvedFile.externalModuleIndicator !== true && isExportAssignment(resolvedFile.externalModuleIndicator) && resolvedFile.externalModuleIndicator.isExportEquals) { diags.push(createDiagnosticForNode(name, Diagnostics.Import_may_be_converted_to_a_default_import)); @@ -141502,12 +141344,11 @@ function containsTopLevelCommonjs(sourceFile) { )); case 244 /* ExpressionStatement */: { const { expression } = statement; - if (!isBinaryExpression(expression)) - return isRequireCall( - expression, - /*requireStringLiteralLikeArgument*/ - true - ); + if (!isBinaryExpression(expression)) return isRequireCall( + expression, + /*requireStringLiteralLikeArgument*/ + true + ); const kind = getAssignmentDeclarationKind(expression); return kind === 1 /* ExportsProperty */ || kind === 2 /* ModuleExports */; } @@ -141578,10 +141419,8 @@ function isPromiseHandler(node) { function hasSupportedNumberOfArguments(node) { const name = node.expression.name.text; const maxArguments = name === "then" ? 2 : name === "catch" ? 1 : name === "finally" ? 1 : 0; - if (node.arguments.length > maxArguments) - return false; - if (node.arguments.length < maxArguments) - return true; + if (node.arguments.length > maxArguments) return false; + if (node.arguments.length < maxArguments) return true; return maxArguments === 1 || some(node.arguments, (arg) => { return arg.kind === 106 /* NullKeyword */ || isIdentifier(arg) && arg.text === "undefined"; }); @@ -141791,8 +141630,7 @@ function transpileWorker(input, transpileOptions, declaration) { /*from*/ result.diagnostics ); - if (outputText === void 0) - return Debug.fail("Output generation failed"); + if (outputText === void 0) return Debug.fail("Output generation failed"); return { outputText, diagnostics, sourceMapText }; } function transpile(input, compilerOptions, fileName, diagnostics, moduleName) { @@ -141829,8 +141667,7 @@ __export(ts_NavigateTo_exports, { // src/services/navigateTo.ts function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles, excludeLibFiles) { const patternMatcher = createPatternMatcher(searchValue); - if (!patternMatcher) - return emptyArray; + if (!patternMatcher) return emptyArray; const rawItems = []; const singleCurrentFile = sourceFiles.length === 1 ? sourceFiles[0] : void 0; for (const sourceFile of sourceFiles) { @@ -141857,8 +141694,7 @@ function getItemsFromNamedDeclaration(patternMatcher, name, declarations, checke return; } for (const declaration of declarations) { - if (!shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile)) - continue; + if (!shouldKeepItem(declaration, checker, excludeLibFiles, singleCurrentFile)) continue; if (patternMatcher.patternContainsDots) { const fullMatch = patternMatcher.getFullMatch(getContainers(declaration), name); if (fullMatch) { @@ -142015,8 +141851,7 @@ function addTrackedEs5Class(name) { trackedEs5Classes.set(name, true); } function endNestedNodes(depth) { - for (let i = 0; i < depth; i++) - endNode(); + for (let i = 0; i < depth; i++) endNode(); } function startNestedNodes(targetNode, entityName) { const names = []; @@ -142024,8 +141859,7 @@ function startNestedNodes(targetNode, entityName) { const name = getNameOrArgument(entityName); const nameText = getElementOrPropertyAccessName(entityName); entityName = entityName.expression; - if (nameText === "prototype" || isPrivateIdentifier(name)) - continue; + if (nameText === "prototype" || isPrivateIdentifier(name)) continue; names.push(name); } names.push(entityName); @@ -142067,8 +141901,7 @@ function addNodeWithRecursiveInitializer(node) { } function hasNavigationBarName(node) { const name = getNameOfDeclaration(node); - if (name === void 0) - return false; + if (name === void 0) return false; if (isComputedPropertyName(name)) { const expression = name.expression; return isEntityNameExpression(expression) || isNumericLiteral(expression) || isStringOrNumericLiteralLike(expression); @@ -142384,8 +142217,7 @@ function tryMergeEs5Class(a, b, bIndex, parent2) { if (parent2.children[bIndex - 1].node.end === lastANode.end) { setTextRange(lastANode, { pos: lastANode.pos, end: bNode.end }); } else { - if (!a.additionalNodes) - a.additionalNodes = []; + if (!a.additionalNodes) a.additionalNodes = []; a.additionalNodes.push(setTextRange( factory.createClassDeclaration( /*modifiers*/ @@ -142697,16 +142529,17 @@ function cleanText(text) { var ts_refactor_exports = {}; __export(ts_refactor_exports, { addExportToChanges: () => addExportToChanges, - addExports: () => addExports, + addExportsInOldFile: () => addExportsInOldFile, + addImportsForMovedSymbols: () => addImportsForMovedSymbols, addNewFileToTsconfig: () => addNewFileToTsconfig, addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, + addTargetFileImports: () => addTargetFileImports, containsJsx: () => containsJsx, convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, createNewFileName: () => createNewFileName, - createOldFileImportsFromTargetFile: () => createOldFileImportsFromTargetFile, deleteMovedStatements: () => deleteMovedStatements, deleteUnusedImports: () => deleteUnusedImports, deleteUnusedOldImports: () => deleteUnusedOldImports, @@ -142717,13 +142550,15 @@ __export(ts_refactor_exports, { generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, getApplicableRefactors: () => getApplicableRefactors, getEditsForRefactor: () => getEditsForRefactor, + getExistingLocals: () => getExistingLocals, + getIdentifierForNode: () => getIdentifierForNode, + getNewStatementsAndRemoveFromOldFile: () => getNewStatementsAndRemoveFromOldFile, getStatementsToMove: () => getStatementsToMove, getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement, getUsageInfo: () => getUsageInfo, inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, isRefactorErrorInfo: () => isRefactorErrorInfo, isTopLevelDeclaration: () => isTopLevelDeclaration, - makeImportOrRequire: () => makeImportOrRequire, moduleSpecifierFromImport: () => moduleSpecifierFromImport, nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration, refactorKindBeginsWith: () => refactorKindBeginsWith, @@ -142766,8 +142601,7 @@ registerRefactor(refactorName, { ], getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { const info = getInfo2(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; return [{ name: refactorName, description: action.description, actions: [action] }]; @@ -142818,8 +142652,7 @@ function getInfo2(context, considerPartialSpans = true) { case 265 /* TypeAliasDeclaration */: case 267 /* ModuleDeclaration */: { const node = exportNode; - if (!node.name) - return void 0; + if (!node.name) return void 0; return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; } case 243 /* VariableStatement */: { @@ -142828,15 +142661,13 @@ function getInfo2(context, considerPartialSpans = true) { return void 0; } const decl = first(vs.declarationList.declarations); - if (!decl.initializer) - return void 0; + if (!decl.initializer) return void 0; Debug.assert(!wasDefault, "Can't have a default flag here"); return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; } case 277 /* ExportAssignment */: { const node = exportNode; - if (node.isExportEquals) - return void 0; + if (node.isExportEquals) return void 0; return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; } default: @@ -142891,8 +142722,7 @@ function changeImports(program, { wasDefault, exportName, exportingModuleSymbol const checker = program.getTypeChecker(); const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { - if (exportName === ref) - return; + if (exportName === ref) return; const importingSourceFile = ref.getSourceFile(); if (wasDefault) { changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); @@ -143019,8 +142849,7 @@ registerRefactor(refactorName2, { kinds: getOwnValues(actions).map((a) => a.kind), getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { const info = getImportConversionInfo(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { const action = actions[info.convertTo]; return [{ name: refactorName2, description: action.description, actions: [action] }]; @@ -143047,12 +142876,10 @@ function getImportConversionInfo(context, considerPartialSpans = true) { const span = getRefactorContextSpan(context); const token = getTokenAtPosition(file, span.start); const importDecl = considerPartialSpans ? findAncestor(token, or(isImportDeclaration, isJSDocImportTag)) : getParentNodeInSpan(token, file, span); - if (importDecl === void 0 || !(isImportDeclaration(importDecl) || isJSDocImportTag(importDecl))) - return { error: "Selection is not an import declaration." }; + if (importDecl === void 0 || !(isImportDeclaration(importDecl) || isJSDocImportTag(importDecl))) return { error: "Selection is not an import declaration." }; const end = span.start + span.length; const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) - return void 0; + if (nextToken && end > nextToken.getStart()) return void 0; const { importClause } = importDecl; if (!importClause) { return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; @@ -143147,7 +142974,7 @@ function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConve toConvertSymbols.add(symbol); } }); - const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; + const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; function hasNamespaceNameConflict(namedImport) { return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { const symbol = checker.resolveName( @@ -143199,8 +143026,7 @@ function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConve } function isExportEqualsModule(moduleSpecifier, checker) { const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) - return false; + if (!externalModule) return false; const exportEquals = checker.resolveExternalModuleSymbol(externalModule); return externalModule !== exportEquals; } @@ -143248,8 +143074,7 @@ registerRefactor(refactorName3, { ], getAvailableActions: function getRefactorActionsToExtractType(context) { const { info, affectedTextRange } = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { const refactorInfo = [{ name: refactorName3, @@ -143317,15 +143142,12 @@ function getRangeToExtract(context, considerEmptySpans = true) { const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const isCursorRequest = range.pos === range.end && considerEmptySpans; const firstType = getFirstTypeAt(file, startPosition, range, isCursorRequest); - if (!firstType || !isTypeNode(firstType)) - return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 }; + if (!firstType || !isTypeNode(firstType)) return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 }; const checker = context.program.getTypeChecker(); const enclosingNode = getEnclosingNode(firstType, isJS); - if (enclosingNode === void 0) - return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 }; + if (enclosingNode === void 0) return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 }; const expandedFirstType = getExpandedSelectionNode(firstType, enclosingNode); - if (!isTypeNode(expandedFirstType)) - return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 }; + if (!isTypeNode(expandedFirstType)) return { info: { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }, affectedTextRange: void 0 }; const typeList = []; if ((isUnionTypeNode(expandedFirstType.parent) || isIntersectionTypeNode(expandedFirstType.parent)) && range.end > firstType.end) { addRange( @@ -143337,8 +143159,7 @@ function getRangeToExtract(context, considerEmptySpans = true) { } const selection = typeList.length > 1 ? typeList : expandedFirstType; const { typeParameters, affectedTextRange } = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) - return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 }; + if (!typeParameters) return { info: { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }, affectedTextRange: void 0 }; const typeElements = flattenTypeLiteralNodeReference(checker, selection); return { info: { isJS, selection, enclosingNode, typeParameters, typeElements }, affectedTextRange }; } @@ -143358,14 +143179,12 @@ function getFirstTypeAt(file, startPosition, range, isCursorRequest) { return void 0; } function flattenTypeLiteralNodeReference(checker, selection) { - if (!selection) - return void 0; + if (!selection) return void 0; if (isArray(selection)) { const result = []; for (const type of selection) { const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers) - return void 0; + if (!flattenedTypeMembers) return void 0; addRange(result, flattenedTypeMembers); } return result; @@ -143396,8 +143215,7 @@ function collectTypeParameters(checker, selection, enclosingNode, file) { const selectionArray = toArray(selection); const selectionRange = { pos: selectionArray[0].getStart(file), end: selectionArray[selectionArray.length - 1].end }; for (const t of selectionArray) { - if (visitor(t)) - return { typeParameters: void 0, affectedTextRange: void 0 }; + if (visitor(t)) return { typeParameters: void 0, affectedTextRange: void 0 }; } return { typeParameters: result, affectedTextRange: selectionRange }; function visitor(node) { @@ -143586,8 +143404,7 @@ function getEnclosingNode(node, isJS) { } function getExpandedSelectionNode(firstType, enclosingNode) { return findAncestor(firstType, (node) => { - if (node === enclosingNode) - return "quit"; + if (node === enclosingNode) return "quit"; if (isUnionTypeNode(node.parent) || isIntersectionTypeNode(node.parent)) { return true; } @@ -143595,282 +143412,12 @@ function getExpandedSelectionNode(firstType, enclosingNode) { }) ?? firstType; } -// src/services/refactors/helpers.ts -function isRefactorErrorInfo(info) { - return info.error !== void 0; -} -function refactorKindBeginsWith(known, requested) { - if (!requested) - return true; - return known.substr(0, requested.length) === requested; -} - -// src/services/refactors/inlineVariable.ts -var refactorName4 = "Inline variable"; -var refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable); -var inlineVariableAction = { - name: refactorName4, - description: refactorDescription, - kind: "refactor.inline.variable" -}; -registerRefactor(refactorName4, { - kinds: [inlineVariableAction.kind], - getAvailableActions(context) { - const { - file, - program, - preferences, - startPosition, - triggerReason - } = context; - const info = getInliningInfo(file, startPosition, triggerReason === "invoked", program); - if (!info) { - return emptyArray; - } - if (!ts_refactor_exports.isRefactorErrorInfo(info)) { - return [{ - name: refactorName4, - description: refactorDescription, - actions: [inlineVariableAction] - }]; - } - if (preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName4, - description: refactorDescription, - actions: [{ - ...inlineVariableAction, - notApplicableReason: info.error - }] - }]; - } - return emptyArray; - }, - getEditsForAction(context, actionName2) { - Debug.assert(actionName2 === refactorName4, "Unexpected refactor invoked"); - const { file, program, startPosition } = context; - const info = getInliningInfo( - file, - startPosition, - /*tryWithReferenceToken*/ - true, - program - ); - if (!info || ts_refactor_exports.isRefactorErrorInfo(info)) { - return void 0; - } - const { references, declaration, replacement } = info; - const edits = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { - for (const node of references) { - tracker.replaceNode(file, node, getReplacementExpression(node, replacement)); - } - tracker.delete(file, declaration); - }); - return { edits }; - } -}); -function getInliningInfo(file, startPosition, tryWithReferenceToken, program) { - var _a, _b; - const checker = program.getTypeChecker(); - const token = getTouchingPropertyName(file, startPosition); - const parent2 = token.parent; - if (!isIdentifier(token)) { - return void 0; - } - if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { - if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) { - return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; - } - if (isDeclarationExported(parent2)) { - return void 0; - } - const references = getReferenceNodes(parent2, checker, file); - return references && { references, declaration: parent2, replacement: parent2.initializer }; - } - if (tryWithReferenceToken) { - let definition = checker.resolveName( - token.text, - token, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); - definition = definition && checker.getMergedSymbol(definition); - if (((_b = definition == null ? void 0 : definition.declarations) == null ? void 0 : _b.length) !== 1) { - return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; - } - const declaration = definition.declarations[0]; - if (!isInitializedVariable(declaration) || !isVariableDeclarationInVariableStatement(declaration) || !isIdentifier(declaration.name)) { - return void 0; - } - if (isDeclarationExported(declaration)) { - return void 0; - } - const references = getReferenceNodes(declaration, checker, file); - return references && { references, declaration, replacement: declaration.initializer }; - } - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) }; -} -function isDeclarationExported(declaration) { - const variableStatement = cast(declaration.parent.parent, isVariableStatement); - return some(variableStatement.modifiers, isExportModifier); -} -function getReferenceNodes(declaration, checker, file) { - const references = []; - const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, (ref) => { - if (ts_FindAllReferences_exports.isWriteAccessForReference(ref) && !isShorthandPropertyAssignment(ref.parent)) { - return true; - } - if (isExportSpecifier(ref.parent) || isExportAssignment(ref.parent)) { - return true; - } - if (isTypeQueryNode(ref.parent)) { - return true; - } - if (textRangeContainsPositionInclusive(declaration, ref.pos)) { - return true; - } - references.push(ref); - }); - return references.length === 0 || cannotInline ? void 0 : references; -} -function getReplacementExpression(reference, replacement) { - replacement = getSynthesizedDeepClone(replacement); - const { parent: parent2 } = reference; - if (isExpression(parent2) && (getExpressionPrecedence(replacement) < getExpressionPrecedence(parent2) || needsParentheses(parent2))) { - return factory.createParenthesizedExpression(replacement); - } - if (isFunctionLike(replacement) && (isCallLikeExpression(parent2) || isPropertyAccessExpression(parent2))) { - return factory.createParenthesizedExpression(replacement); - } - if (isPropertyAccessExpression(parent2) && (isNumericLiteral(replacement) || isObjectLiteralExpression(replacement))) { - return factory.createParenthesizedExpression(replacement); - } - if (isIdentifier(reference) && isShorthandPropertyAssignment(parent2)) { - return factory.createPropertyAssignment(reference, replacement); - } - return replacement; -} - -// src/services/refactors/moveToNewFile.ts -var refactorName5 = "Move to a new file"; -var description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); -var moveToNewFileAction = { - name: refactorName5, - description, - kind: "refactor.move.newFile" -}; -registerRefactor(refactorName5, { - kinds: [moveToNewFileAction.kind], - getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { - const statements = getStatementsToMove(context); - if (context.preferences.allowTextChangesInNewFiles && statements) { - const file = context.file; - const affectedTextRange = { - start: { line: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).line, offset: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).character }, - end: { line: getLineAndCharacterOfPosition(file, last(statements.all).end).line, offset: getLineAndCharacterOfPosition(file, last(statements.all).end).character } - }; - return [{ name: refactorName5, description, actions: [{ ...moveToNewFileAction, range: affectedTextRange }] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ name: refactorName5, description, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { - Debug.assert(actionName2 === refactorName5, "Wrong refactor invoked"); - const statements = Debug.checkDefined(getStatementsToMove(context)); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context.file, context.program, statements, t, context.host, context.preferences)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } -}); -function doChange3(oldFile, program, toMove, changes, host, preferences) { - const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); - const newFilename = createNewFileName(oldFile, program, host, toMove); - changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); - addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); -} -function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { - const checker = program.getTypeChecker(); - const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [...prologueDirectives, ...toMove.all]; - } - const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator); - const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference); - if (importsFromNewFile) { - insertImports( - changes, - oldFile, - importsFromNewFile, - /*blankLineBetween*/ - true, - preferences - ); - } - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); - const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); - if (imports.length && body.length) { - return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */, - ...body - ]; - } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; -} -function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { - const copiedOldImports = []; - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - } - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - newFileImportsFromOldFile.forEach((symbol) => { - if (!symbol.declarations) { - return; - } - for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - } - if (hasSyntacticModifier(decl, 2048 /* Default */)) { - oldFileDefault = name; - } else { - oldFileNamedImports.push(name.text); - } - } - }); - append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); - return copiedOldImports; -} - // src/services/refactors/moveToFile.ts var refactorNameForMoveToFile = "Move to file"; -var description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file); +var description = getLocaleSpecificMessage(Diagnostics.Move_to_file); var moveToFileAction = { name: "Move to file", - description: description2, + description, kind: "refactor.move.file" }; registerRefactor(refactorNameForMoveToFile, { @@ -143881,7 +143428,7 @@ registerRefactor(refactorNameForMoveToFile, { if (!interactiveRefactorArguments) { return emptyArray; } - if (context.endPosition !== void 0) { + if (context.triggerReason === "implicit" && context.endPosition !== void 0) { const startNodeAncestor = findAncestor(getTokenAtPosition(file, context.startPosition), isBlockLike); const endNodeAncestor = findAncestor(getTokenAtPosition(file, context.endPosition), isBlockLike); if (startNodeAncestor && !isSourceFile(startNodeAncestor) && endNodeAncestor && !isSourceFile(endNodeAncestor)) { @@ -143893,10 +143440,10 @@ registerRefactor(refactorNameForMoveToFile, { start: { line: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).line, offset: getLineAndCharacterOfPosition(file, statements.all[0].getStart(file)).character }, end: { line: getLineAndCharacterOfPosition(file, last(statements.all).end).line, offset: getLineAndCharacterOfPosition(file, last(statements.all).end).character } }; - return [{ name: refactorNameForMoveToFile, description: description2, actions: [{ ...moveToFileAction, range: affectedTextRange }] }]; + return [{ name: refactorNameForMoveToFile, description, actions: [{ ...moveToFileAction, range: affectedTextRange }] }]; } if (context.preferences.provideRefactorNotApplicableReason) { - return [{ name: refactorNameForMoveToFile, description: description2, actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; + return [{ name: refactorNameForMoveToFile, description, actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; } return emptyArray; }, @@ -143910,7 +143457,7 @@ registerRefactor(refactorNameForMoveToFile, { if (host.fileExists(targetFile) && program.getSourceFile(targetFile) === void 0) { return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_statements_to_the_selected_file)); } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); return { edits, renameFilename: void 0, renameLocation: void 0 }; } return error(getLocaleSpecificMessage(Diagnostics.Cannot_move_to_file_selected_file_is_invalid)); @@ -143919,149 +143466,50 @@ registerRefactor(refactorNameForMoveToFile, { function error(notApplicableReason) { return { edits: [], renameFilename: void 0, renameLocation: void 0, notApplicableReason }; } -function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { +function doChange3(context, oldFile, targetFile, program, toMove, changes, host, preferences) { const checker = program.getTypeChecker(); - if (!host.fileExists(targetFile)) { - changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, getUsageInfo(oldFile, toMove.all, checker), changes, toMove, program, host, preferences)); + const isForNewFile = !host.fileExists(targetFile); + const targetSourceFile = isForNewFile ? createFutureSourceFile(targetFile, oldFile.externalModuleIndicator ? 99 /* ESNext */ : oldFile.commonJsModuleIndicator ? 1 /* CommonJS */ : void 0, program, host) : Debug.checkDefined(program.getSourceFile(targetFile)); + const importAdderForOldFile = ts_codefix_exports.createImportAdder(oldFile, context.program, context.preferences, context.host); + const importAdderForNewFile = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile(oldFile, targetSourceFile, getUsageInfo(oldFile, toMove.all, checker, isForNewFile ? void 0 : getExistingLocals(targetSourceFile, toMove.all, checker)), changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile); + if (isForNewFile) { addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); - } else { - const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); - const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); - getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, getUsageInfo(oldFile, toMove.all, checker, getExistingLocals(targetSourceFile, toMove.all, checker)), changes, toMove, program, host, preferences, importAdder); } } -function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { +function getNewStatementsAndRemoveFromOldFile(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile) { const checker = program.getTypeChecker(); const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [...prologueDirectives, ...toMove.all]; - } - const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; - const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, program, host, !!oldFile.commonJsModuleIndicator); const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); - if (importsFromTargetFile) { - insertImports( - changes, - oldFile, - importsFromTargetFile, + addImportsForMovedSymbols(usage.oldFileImportsFromTargetFile, targetFile.fileName, importAdderForOldFile, program); + deleteUnusedOldImports(oldFile, toMove.all, usage.unusedImportsFromOldFile, importAdderForOldFile); + importAdderForOldFile.writeFixes(changes, quotePreference); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFile.fileName, quotePreference); + addExportsInOldFile(oldFile, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax); + addTargetFileImports(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, checker, program, importAdderForNewFile); + if (!isFullSourceFile(targetFile) && prologueDirectives.length) { + changes.insertStatementsInNewFile(targetFile.fileName, prologueDirectives, oldFile); + } + importAdderForNewFile.writeFixes(changes, quotePreference); + const body = addExports(oldFile, toMove.all, arrayFrom(usage.oldFileImportsFromTargetFile.keys()), useEsModuleSyntax); + if (isFullSourceFile(targetFile) && targetFile.statements.length > 0) { + moveStatementsToTargetFile(changes, program, body, targetFile, toMove); + } else if (isFullSourceFile(targetFile)) { + changes.insertNodesAtEndOfFile( + targetFile, + body, /*blankLineBetween*/ - true, - preferences + false ); - } - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference); - const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); - if (typeof targetFile !== "string") { - if (targetFile.statements.length > 0) { - moveStatementsToTargetFile(changes, program, body, targetFile, toMove); - } else { - changes.insertNodesAtEndOfFile( - targetFile, - body, - /*blankLineBetween*/ - false - ); - } - if (imports.length > 0) { - insertImports( - changes, - targetFile, - imports, - /*blankLineBetween*/ - true, - preferences - ); - } - } - if (importAdder) { - importAdder.writeFixes(changes, quotePreference); - } - if (imports.length && body.length) { - return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */, - ...body - ]; - } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; -} -function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { - const copiedOldImports = []; - if (importAdder) { - importsToCopy.forEach((isValidTypeOnlyUseSite, symbol) => { - try { - importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite); - } catch { - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - } - } - }); } else { - const targetSourceFile = program.getSourceFile(targetFile); - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - var _a; - const moduleSpecifier = moduleSpecifierFromImport(i); - const compilerOptions = program.getCompilerOptions(); - const resolved = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier); - const fileName = (_a = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _a.resolvedFileName; - if (fileName && targetSourceFile) { - const newModuleSpecifier = getModuleSpecifier(compilerOptions, targetSourceFile, targetSourceFile.fileName, fileName, createModuleSpecifierResolutionHost(program, host)); - append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - } else { - append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - } - }); - } + changes.insertStatementsInNewFile(targetFile.fileName, importAdderForNewFile.hasFixes() ? [4 /* NewLineTrivia */, ...body] : body, oldFile); } - const targetFileSourceFile = program.getSourceFile(targetFile); - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - targetFileImportsFromOldFile.forEach((symbol) => { - if (!symbol.declarations) { - return; - } - for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - } - if (importAdder && checker.isUnknownSymbol(symbol)) { - importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); - } else { - if (hasSyntacticModifier(decl, 2048 /* Default */)) { - oldFileDefault = name; - } else { - oldFileNamedImports.push(name.text); - } - } - } - }); - return targetFileSourceFile ? append(copiedOldImports, makeImportOrRequire(targetFileSourceFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)) : append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, oldFile.fileName, program, host, useEsModuleSyntax, quotePreference)); } function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { const cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; + if (!cfg) return; const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); const newFilePath = getRelativePathFromFile(cfg.fileName, newFileAbsolutePath, getCanonicalFileName); const cfgObject = cfg.statements[0] && tryCast(cfg.statements[0].expression, isObjectLiteralExpression); @@ -144075,37 +143523,54 @@ function deleteMovedStatements(sourceFile, moved, changes) { changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); } } -function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { +function deleteUnusedOldImports(oldFile, toMove, toDelete, importAdder) { for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); + if (contains(toMove, statement)) continue; + forEachImportInStatement(statement, (i) => { + forEachAliasDeclarationInImportOrRequire(i, (decl) => { + if (toDelete.has(decl.symbol)) { + importAdder.removeExistingImport(decl); + } + }); + }); } } +function addExportsInOldFile(oldFile, targetFileImportsFromOldFile, changes, useEsModuleSyntax) { + const markSeenTop = nodeSeenTracker(); + targetFileImportsFromOldFile.forEach((_, symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + } + }); +} function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) { const checker = program.getTypeChecker(); for (const sourceFile of program.getSourceFiles()) { - if (sourceFile === oldFile) - continue; + if (sourceFile === oldFile) continue; for (const statement of sourceFile.statements) { forEachImportInStatement(statement, (importNode) => { - if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) - return; + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; const shouldMove = (name) => { const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); return !!symbol && movedSymbols.has(symbol); }; deleteUnusedImports(sourceFile, importNode, changes, shouldMove); const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(getNormalizedAbsolutePath(oldFile.fileName, program.getCurrentDirectory())), targetFileName); - if (getStringComparer(!program.useCaseSensitiveFileNames())(pathToTargetFileWithExtension, sourceFile.fileName) === 0 /* EqualTo */) - return; + if (getStringComparer(!program.useCaseSensitiveFileNames())(pathToTargetFileWithExtension, sourceFile.fileName) === 0 /* EqualTo */) return; const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.fileName, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); - if (newImportDeclaration) - changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + if (newImportDeclaration) changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); const ns = getNamespaceLikeImport(importNode); - if (ns) - updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); + if (ns) updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); }); } } @@ -144123,12 +143588,11 @@ function getNamespaceLikeImport(node) { } } function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { - const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); + const preferredNewNamespaceName = moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); let needUniqueName = false; const toChange = []; ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { - if (!isPropertyAccessExpression(ref.parent)) - return; + if (!isPropertyAccessExpression(ref.parent)) return; needUniqueName = needUniqueName || !!checker.resolveName( preferredNewNamespaceName, ref, @@ -144202,8 +143666,7 @@ function moduleSpecifierFromImport(i) { } function forEachImportInStatement(statement, cb) { if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) - cb(statement); + if (isStringLiteral(statement.moduleSpecifier)) cb(statement); } else if (isImportEqualsDeclaration(statement)) { if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { cb(statement); @@ -144220,45 +143683,39 @@ function forEachImportInStatement(statement, cb) { } } } -function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - let defaultImport; - const imports = []; - targetFileNeedExport.forEach((symbol) => { - if (symbol.escapedName === "default" /* Default */) { - defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); - } else { - imports.push(symbol.name); +function forEachAliasDeclarationInImportOrRequire(importOrRequire, cb) { + var _a, _b, _c, _d, _e; + if (importOrRequire.kind === 272 /* ImportDeclaration */) { + if ((_a = importOrRequire.importClause) == null ? void 0 : _a.name) { + cb(importOrRequire.importClause); } - }); - return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference); + if (((_c = (_b = importOrRequire.importClause) == null ? void 0 : _b.namedBindings) == null ? void 0 : _c.kind) === 274 /* NamespaceImport */) { + cb(importOrRequire.importClause.namedBindings); + } + if (((_e = (_d = importOrRequire.importClause) == null ? void 0 : _d.namedBindings) == null ? void 0 : _e.kind) === 275 /* NamedImports */) { + for (const element of importOrRequire.importClause.namedBindings.elements) { + cb(element); + } + } + } else if (importOrRequire.kind === 271 /* ImportEqualsDeclaration */) { + cb(importOrRequire); + } else if (importOrRequire.kind === 260 /* VariableDeclaration */) { + if (importOrRequire.name.kind === 80 /* Identifier */) { + cb(importOrRequire); + } else if (importOrRequire.name.kind === 206 /* ObjectBindingPattern */) { + for (const element of importOrRequire.name.elements) { + if (isIdentifier(element.name)) { + cb(element); + } + } + } + } } -function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - const pathToTargetFile = resolvePath(getDirectoryPath(getNormalizedAbsolutePath(sourceFile.fileName, program.getCurrentDirectory())), targetFileNameWithExtension); - const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.fileName, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); - if (useEs6Imports) { - const specifiers = imports.map((i) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - factory.createIdentifier(i) - )); - return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference); - } else { - Debug.assert(!defaultImport, "No default import should exist"); - const bindingElements = imports.map((i) => factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - i - )); - return bindingElements.length ? makeVariableStatement( - factory.createObjectBindingPattern(bindingElements), - /*type*/ - void 0, - createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference)) - ) : void 0; +function addImportsForMovedSymbols(symbols, targetFileName, importAdder, program) { + for (const [symbol, isValidTypeOnlyUseSite] of symbols) { + const symbolName2 = getNameForExportedSymbol(symbol, getEmitScriptTarget(program.getCompilerOptions())); + const exportKind = symbol.name === "default" && symbol.parent ? 1 /* Default */ : 0 /* Named */; + importAdder.addImportForNonExistentExport(symbolName2, targetFileName, exportKind, symbol.flags, isValidTypeOnlyUseSite); } } function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { @@ -144278,11 +143735,10 @@ function addExports(sourceFile, toMove, needExport, useEs6Exports) { return flatMap(toMove, (statement) => { if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { var _a; - return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); + return needExport.includes(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); })) { const exports2 = addExport(getSynthesizedDeepClone(statement), useEs6Exports); - if (exports2) - return exports2; + if (exports2) return exports2; } return getSynthesizedDeepClone(statement); }); @@ -144295,86 +143751,17 @@ function isExported(sourceFile, decl, useEs6Exports, name) { return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); } function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { - switch (importDecl.kind) { - case 272 /* ImportDeclaration */: - deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); - break; - case 271 /* ImportEqualsDeclaration */: - if (isUnused(importDecl.name)) { - changes.delete(sourceFile, importDecl); - } - break; - case 260 /* VariableDeclaration */: - deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); - break; - default: - Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); - } -} -function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) - return; - const { name, namedBindings } = importDecl.importClause; - const defaultUnused = !name || isUnused(name); - const namedBindingsUnused = !namedBindings || (namedBindings.kind === 274 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); - if (defaultUnused && namedBindingsUnused) { - changes.delete(sourceFile, importDecl); - } else { - if (name && defaultUnused) { - changes.delete(sourceFile, name); - } - if (namedBindings) { - if (namedBindingsUnused) { - changes.replaceNode( - sourceFile, - importDecl.importClause, - factory.updateImportClause( - importDecl.importClause, - importDecl.importClause.isTypeOnly, - name, - /*namedBindings*/ - void 0 - ) - ); - } else if (namedBindings.kind === 275 /* NamedImports */) { - for (const element of namedBindings.elements) { - if (isUnused(element.name)) - changes.delete(sourceFile, element); - } - } + if (importDecl.kind === 272 /* ImportDeclaration */ && importDecl.importClause) { + const { name, namedBindings } = importDecl.importClause; + if ((!name || isUnused(name)) && (!namedBindings || namedBindings.kind === 275 /* NamedImports */ && namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name)))) { + return changes.delete(sourceFile, importDecl); } } -} -function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name } = varDecl; - switch (name.kind) { - case 80 /* Identifier */: - if (isUnused(name)) { - if (varDecl.initializer && isRequireCall( - varDecl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { - changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && length(varDecl.parent.declarations) === 1 ? varDecl.parent.parent : varDecl); - } else { - changes.delete(sourceFile, name); - } - } - break; - case 207 /* ArrayBindingPattern */: - break; - case 206 /* ObjectBindingPattern */: - if (name.elements.every((e) => isIdentifier(e.name) && isUnused(e.name))) { - changes.delete(sourceFile, isVariableDeclarationList(varDecl.parent) && varDecl.parent.declarations.length === 1 ? varDecl.parent.parent : varDecl); - } else { - for (const element of name.elements) { - if (isIdentifier(element.name) && isUnused(element.name)) { - changes.delete(sourceFile, element.name); - } - } - } - break; - } + forEachAliasDeclarationInImportOrRequire(importDecl, (i) => { + if (i.name && isIdentifier(i.name) && isUnused(i.name)) { + changes.delete(sourceFile, i); + } + }); } function isTopLevelDeclarationStatement(node) { Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); @@ -144444,8 +143831,7 @@ function filterImport(i, moduleSpecifier, keep) { switch (i.kind) { case 272 /* ImportDeclaration */: { const clause = i.importClause; - if (!clause) - return void 0; + if (!clause) return void 0; const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); return defaultImport || namedBindings ? factory.createImportDeclaration( @@ -144503,15 +143889,12 @@ function getTopLevelDeclarationStatement(d) { } } function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) - return; + if (isExported(sourceFile, decl, useEs6Exports, name)) return; if (useEs6Exports) { - if (!isExpressionStatement(decl)) - changes.insertExportModifier(sourceFile, decl); + if (!isExpressionStatement(decl)) changes.insertExportModifier(sourceFile, decl); } else { const names = getNamesToExportInCommonJS(decl); - if (names.length !== 0) - changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + if (names.length !== 0) changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); } } function createNewFileName(oldFile, program, host, toMove) { @@ -144541,8 +143924,7 @@ function getRangeToMove(context) { const range = createTextRangeFromSpan(getRefactorContextSpan(context)); const { statements } = file; let startNodeIndex = findIndex(statements, (s) => s.end > range.pos); - if (startNodeIndex === -1) - return void 0; + if (startNodeIndex === -1) return void 0; const startStatement = statements[startNodeIndex]; const overloadRangeToMove = getOverloadRangeToMove(file, startStatement); if (overloadRangeToMove) { @@ -144563,14 +143945,12 @@ function getRangeToMove(context) { } function getStatementsToMove(context) { const rangeToMove = getRangeToMove(context); - if (rangeToMove === void 0) - return void 0; + if (rangeToMove === void 0) return void 0; const all = []; const ranges = []; const { toMove, afterLast } = rangeToMove; getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { - for (let i = start; i < afterEndIndex; i++) - all.push(toMove[i]); + for (let i = start; i < afterEndIndex; i++) all.push(toMove[i]); ranges.push({ first: toMove[start], afterLast }); }); return all.length === 0 ? void 0 : { all, ranges }; @@ -144598,12 +143978,13 @@ function isPureImport(node) { } } function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PURE__ */ new Set()) { + var _a; const movedSymbols = /* @__PURE__ */ new Set(); const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); - const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); + const targetFileImportsFromOldFile = /* @__PURE__ */ new Map(); const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx(toMove)); if (jsxNamespaceSymbol) { - oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); + oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, [false, tryCast((_a = jsxNamespaceSymbol.declarations) == null ? void 0 : _a[0], (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d))]); } for (const statement of toMove) { forEachTopLevelDeclaration(statement, (decl) => { @@ -144623,9 +144004,12 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR for (const decl of symbol.declarations) { if (isInImport(decl)) { const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); - oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite); + oldImportsNeededByTargetFile.set(symbol, [ + prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite, + tryCast(decl, (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d)) + ]); } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { - targetFileImportsFromOldFile.add(symbol); + targetFileImportsFromOldFile.set(symbol, isValidTypeOnlyUseSite); } } }); @@ -144633,16 +144017,14 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR for (const unusedImport of oldImportsNeededByTargetFile.keys()) { unusedImportsFromOldFile.add(unusedImport); } - const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + const oldFileImportsFromTargetFile = /* @__PURE__ */ new Map(); for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; + if (contains(toMove, statement)) continue; if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { unusedImportsFromOldFile.delete(jsxNamespaceSymbol); } - forEachReference(statement, checker, (symbol) => { - if (movedSymbols.has(symbol)) - oldFileImportsFromTargetFile.add(symbol); + forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + if (movedSymbols.has(symbol)) oldFileImportsFromTargetFile.set(symbol, isValidTypeOnlyUseSite); unusedImportsFromOldFile.delete(symbol); }); } @@ -144666,8 +144048,7 @@ function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { let newFilename = proposedFilename; for (let i = 1; ; i++) { const name = combinePaths(inDirectory, newFilename + extension); - if (!host.fileExists(name)) - return newFilename; + if (!host.fileExists(name)) return newFilename; newFilename = `${proposedFilename}.${i}`; } } @@ -144678,8 +144059,7 @@ function forEachReference(node, checker, onReference) { node.forEachChild(function cb(node2) { if (isIdentifier(node2) && !isDeclarationName(node2)) { const sym = checker.getSymbolAtLocation(node2); - if (sym) - onReference(sym, isValidTypeOnlyAliasUseSite(node2)); + if (sym) onReference(sym, isValidTypeOnlyAliasUseSite(node2)); } else { node2.forEachChild(cb); } @@ -144842,7 +144222,7 @@ function getExistingLocals(sourceFile, statements, checker) { for (const statement of statements) { forEachReference(statement, checker, (s) => { const symbol = skipAlias(s, checker); - if (symbol.valueDeclaration && getSourceFileOfNode(symbol.valueDeclaration) === sourceFile) { + if (symbol.valueDeclaration && getSourceFileOfNode(symbol.valueDeclaration).path === sourceFile.path) { existingLocals.add(symbol); } }); @@ -144850,6 +144230,234 @@ function getExistingLocals(sourceFile, statements, checker) { return existingLocals; } +// src/services/refactors/helpers.ts +function isRefactorErrorInfo(info) { + return info.error !== void 0; +} +function refactorKindBeginsWith(known, requested) { + if (!requested) return true; + return known.substr(0, requested.length) === requested; +} +function getIdentifierForNode(node, scope, checker, file) { + return isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( + node.name.text, + node, + 111551 /* Value */, + /*excludeGlobals*/ + false + ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); +} +function addTargetFileImports(oldFile, importsToCopy, targetFileImportsFromOldFile, checker, program, importAdder) { + importsToCopy.forEach(([isValidTypeOnlyUseSite, declaration], symbol) => { + var _a; + const targetSymbol = skipAlias(symbol, checker); + if (checker.isUnknownSymbol(targetSymbol)) { + importAdder.addVerbatimImport(Debug.checkDefined(declaration ?? findAncestor((_a = symbol.declarations) == null ? void 0 : _a[0], isAnyImportOrRequireStatement))); + } else { + importAdder.addImportFromExportedSymbol(targetSymbol, isValidTypeOnlyUseSite, declaration); + } + }); + addImportsForMovedSymbols(targetFileImportsFromOldFile, oldFile.fileName, importAdder, program); +} + +// src/services/refactors/inlineVariable.ts +var refactorName4 = "Inline variable"; +var refactorDescription = getLocaleSpecificMessage(Diagnostics.Inline_variable); +var inlineVariableAction = { + name: refactorName4, + description: refactorDescription, + kind: "refactor.inline.variable" +}; +registerRefactor(refactorName4, { + kinds: [inlineVariableAction.kind], + getAvailableActions(context) { + const { + file, + program, + preferences, + startPosition, + triggerReason + } = context; + const info = getInliningInfo(file, startPosition, triggerReason === "invoked", program); + if (!info) { + return emptyArray; + } + if (!ts_refactor_exports.isRefactorErrorInfo(info)) { + return [{ + name: refactorName4, + description: refactorDescription, + actions: [inlineVariableAction] + }]; + } + if (preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName4, + description: refactorDescription, + actions: [{ + ...inlineVariableAction, + notApplicableReason: info.error + }] + }]; + } + return emptyArray; + }, + getEditsForAction(context, actionName2) { + Debug.assert(actionName2 === refactorName4, "Unexpected refactor invoked"); + const { file, program, startPosition } = context; + const info = getInliningInfo( + file, + startPosition, + /*tryWithReferenceToken*/ + true, + program + ); + if (!info || ts_refactor_exports.isRefactorErrorInfo(info)) { + return void 0; + } + const { references, declaration, replacement } = info; + const edits = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { + for (const node of references) { + tracker.replaceNode(file, node, getReplacementExpression(node, replacement)); + } + tracker.delete(file, declaration); + }); + return { edits }; + } +}); +function getInliningInfo(file, startPosition, tryWithReferenceToken, program) { + var _a, _b; + const checker = program.getTypeChecker(); + const token = getTouchingPropertyName(file, startPosition); + const parent2 = token.parent; + if (!isIdentifier(token)) { + return void 0; + } + if (isInitializedVariable(parent2) && isVariableDeclarationInVariableStatement(parent2) && isIdentifier(parent2.name)) { + if (((_a = checker.getMergedSymbol(parent2.symbol).declarations) == null ? void 0 : _a.length) !== 1) { + return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; + } + if (isDeclarationExported(parent2)) { + return void 0; + } + const references = getReferenceNodes(parent2, checker, file); + return references && { references, declaration: parent2, replacement: parent2.initializer }; + } + if (tryWithReferenceToken) { + let definition = checker.resolveName( + token.text, + token, + 111551 /* Value */, + /*excludeGlobals*/ + false + ); + definition = definition && checker.getMergedSymbol(definition); + if (((_b = definition == null ? void 0 : definition.declarations) == null ? void 0 : _b.length) !== 1) { + return { error: getLocaleSpecificMessage(Diagnostics.Variables_with_multiple_declarations_cannot_be_inlined) }; + } + const declaration = definition.declarations[0]; + if (!isInitializedVariable(declaration) || !isVariableDeclarationInVariableStatement(declaration) || !isIdentifier(declaration.name)) { + return void 0; + } + if (isDeclarationExported(declaration)) { + return void 0; + } + const references = getReferenceNodes(declaration, checker, file); + return references && { references, declaration, replacement: declaration.initializer }; + } + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_variable_to_inline) }; +} +function isDeclarationExported(declaration) { + const variableStatement = cast(declaration.parent.parent, isVariableStatement); + return some(variableStatement.modifiers, isExportModifier); +} +function getReferenceNodes(declaration, checker, file) { + const references = []; + const cannotInline = ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(declaration.name, checker, file, (ref) => { + if (ts_FindAllReferences_exports.isWriteAccessForReference(ref) && !isShorthandPropertyAssignment(ref.parent)) { + return true; + } + if (isExportSpecifier(ref.parent) || isExportAssignment(ref.parent)) { + return true; + } + if (isTypeQueryNode(ref.parent)) { + return true; + } + if (textRangeContainsPositionInclusive(declaration, ref.pos)) { + return true; + } + references.push(ref); + }); + return references.length === 0 || cannotInline ? void 0 : references; +} +function getReplacementExpression(reference, replacement) { + replacement = getSynthesizedDeepClone(replacement); + const { parent: parent2 } = reference; + if (isExpression(parent2) && (getExpressionPrecedence(replacement) < getExpressionPrecedence(parent2) || needsParentheses(parent2))) { + return factory.createParenthesizedExpression(replacement); + } + if (isFunctionLike(replacement) && (isCallLikeExpression(parent2) || isPropertyAccessExpression(parent2))) { + return factory.createParenthesizedExpression(replacement); + } + if (isPropertyAccessExpression(parent2) && (isNumericLiteral(replacement) || isObjectLiteralExpression(replacement))) { + return factory.createParenthesizedExpression(replacement); + } + if (isIdentifier(reference) && isShorthandPropertyAssignment(parent2)) { + return factory.createPropertyAssignment(reference, replacement); + } + return replacement; +} + +// src/services/refactors/moveToNewFile.ts +var refactorName5 = "Move to a new file"; +var description2 = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); +var moveToNewFileAction = { + name: refactorName5, + description: description2, + kind: "refactor.move.newFile" +}; +registerRefactor(refactorName5, { + kinds: [moveToNewFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { + const statements = getStatementsToMove(context); + const file = context.file; + if (context.triggerReason === "implicit" && context.endPosition !== void 0) { + const startNodeAncestor = findAncestor(getTokenAtPosition(file, context.startPosition), isBlockLike); + const endNodeAncestor = findAncestor(getTokenAtPosition(file, context.endPosition), isBlockLike); + if (startNodeAncestor && !isSourceFile(startNodeAncestor) && endNodeAncestor && !isSourceFile(endNodeAncestor)) { + return emptyArray; + } + } + if (context.preferences.allowTextChangesInNewFiles && statements) { + const file2 = context.file; + const affectedTextRange = { + start: { line: getLineAndCharacterOfPosition(file2, statements.all[0].getStart(file2)).line, offset: getLineAndCharacterOfPosition(file2, statements.all[0].getStart(file2)).character }, + end: { line: getLineAndCharacterOfPosition(file2, last(statements.all).end).line, offset: getLineAndCharacterOfPosition(file2, last(statements.all).end).character } + }; + return [{ name: refactorName5, description: description2, actions: [{ ...moveToNewFileAction, range: affectedTextRange }] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ name: refactorName5, description: description2, actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { + Debug.assert(actionName2 === refactorName5, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context.file, context.program, statements, t, context.host, context, context.preferences)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } +}); +function doChange4(oldFile, program, toMove, changes, host, context, preferences) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + const newFilename = createNewFileName(oldFile, program, host, toMove); + const newSourceFile = createFutureSourceFile(newFilename, oldFile.externalModuleIndicator ? 99 /* ESNext */ : oldFile.commonJsModuleIndicator ? 1 /* CommonJS */ : void 0, program, host); + const importAdderForOldFile = ts_codefix_exports.createImportAdder(oldFile, context.program, context.preferences, context.host); + const importAdderForNewFile = ts_codefix_exports.createImportAdder(newSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile(oldFile, newSourceFile, usage, changes, toMove, program, host, preferences, importAdderForNewFile, importAdderForOldFile); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); +} + // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; @@ -144869,8 +144477,7 @@ registerRefactor(refactorName6, { function getRefactorActionsToConvertOverloadsToOneSignature(context) { const { file, startPosition, program } = context; const info = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!info) - return emptyArray; + if (!info) return emptyArray; return [{ name: refactorName6, description: refactorDescription2, @@ -144880,8 +144487,7 @@ function getRefactorActionsToConvertOverloadsToOneSignature(context) { function getRefactorEditsToConvertOverloadsToOneSignature(context) { const { file, startPosition, program } = context; const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!signatureDecls) - return void 0; + if (!signatureDecls) return void 0; const checker = program.getTypeChecker(); const lastDeclaration = signatureDecls[signatureDecls.length - 1]; let updated = lastDeclaration; @@ -145089,8 +144695,7 @@ registerRefactor(refactorName7, { function getRefactorActionsToRemoveFunctionBraces(context) { const { file, startPosition, triggerReason } = context; const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName7, @@ -145233,8 +144838,7 @@ registerRefactor(refactorName8, { function getRefactorActionsToConvertFunctionExpressions(context) { const { file, startPosition, program, kind } = context; const info = getFunctionInfo(file, startPosition, program); - if (!info) - return emptyArray; + if (!info) return emptyArray; const { selectedVariableDeclaration, func } = info; const possibleActions = []; const errors = []; @@ -145271,8 +144875,7 @@ function getRefactorActionsToConvertFunctionExpressions(context) { function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { const { file, startPosition, program } = context; const info = getFunctionInfo(file, startPosition, program); - if (!info) - return void 0; + if (!info) return void 0; const { func } = info; const edits = []; switch (actionName2) { @@ -145281,13 +144884,11 @@ function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { break; case toNamedFunctionAction.name: const variableInfo = getVariableInfo(func); - if (!variableInfo) - return void 0; + if (!variableInfo) return void 0; edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); break; case toArrowFunctionAction.name: - if (!isFunctionExpression(func)) - return void 0; + if (!isFunctionExpression(func)) return void 0; edits.push(...getEditInfoForConvertToArrowFunction(context, func)); break; default: @@ -145317,8 +144918,7 @@ function getFunctionInfo(file, startPosition, program) { } const maybeFunc = getContainingFunction(token); if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) - return void 0; + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) return void 0; return { selectedVariableDeclaration: false, func: maybeFunc }; } return void 0; @@ -145363,12 +144963,10 @@ function convertToBlock(body) { } function getVariableInfo(func) { const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) - return void 0; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) return void 0; const variableDeclarationList = variableDeclaration.parent; const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) - return void 0; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) return void 0; return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; } function getEditInfoForConvertToAnonymousFunction(context, func) { @@ -145445,11 +145043,9 @@ registerRefactor(refactorName9, { function getRefactorActionsToConvertParametersToDestructuredObject(context) { const { file, startPosition } = context; const isJSFile = isSourceFileJS(file); - if (isJSFile) - return emptyArray; + if (isJSFile) return emptyArray; const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!functionDeclaration) - return emptyArray; + if (!functionDeclaration) return emptyArray; return [{ name: refactorName9, description: refactorDescription5, @@ -145460,8 +145056,7 @@ function getRefactorEditsToConvertParametersToDestructuredObject(context, action Debug.assert(actionName2 === refactorName9, "Unexpected action name"); const { file, startPosition, program, cancellationToken, host } = context; const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!functionDeclaration || !cancellationToken) - return void 0; + if (!functionDeclaration || !cancellationToken) return void 0; const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); if (groupedReferences.valid) { const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences)); @@ -145703,10 +145298,8 @@ function entryToType(entry) { function getFunctionDeclarationAtPosition(file, startPosition, checker) { const node = getTouchingToken(file, startPosition); const functionDeclaration = getContainingFunctionDeclaration(node); - if (isTopLevelJSDoc(node)) - return void 0; - if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) - return functionDeclaration; + if (isTopLevelJSDoc(node)) return void 0; + if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration; return void 0; } function isTopLevelJSDoc(node) { @@ -145722,8 +145315,7 @@ function isValidMethodSignature(node) { } function isValidFunctionDeclaration(functionDeclaration, checker) { var _a; - if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) - return false; + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case 262 /* FunctionDeclaration */: return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); @@ -145765,8 +145357,7 @@ function isValidParameterNodeArray(parameters, checker) { function isValidParameterDeclaration(parameterDeclaration, checker) { if (isRestParameter(parameterDeclaration)) { const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) - return false; + if (!checker.isArrayType(type) && !checker.isTupleType(type)) return false; } return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); } @@ -145802,8 +145393,7 @@ function createNewArgument(functionDeclaration, functionArguments) { const parameterName = getParameterName(parameters[i]); const property = createPropertyOrShorthandAssignment(parameterName, arg); suppressLeadingAndTrailingTrivia(property.name); - if (isPropertyAssignment(property)) - suppressLeadingAndTrailingTrivia(property.initializer); + if (isPropertyAssignment(property)) suppressLeadingAndTrailingTrivia(property.initializer); copyComments(arg, property); return property; }); @@ -145919,8 +145509,7 @@ function getClassNames(constructorDeclaration) { switch (constructorDeclaration.parent.kind) { case 263 /* ClassDeclaration */: const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) - return [classDeclaration.name]; + if (classDeclaration.name) return [classDeclaration.name]; const defaultModifier = Debug.checkDefined( findModifier(classDeclaration, 90 /* DefaultKeyword */), "Nameless class declaration should be a default export" @@ -145930,16 +145519,14 @@ function getClassNames(constructorDeclaration) { const classExpression = constructorDeclaration.parent; const variableDeclaration = constructorDeclaration.parent.parent; const className = classExpression.name; - if (className) - return [className, variableDeclaration.name]; + if (className) return [className, variableDeclaration.name]; return [variableDeclaration.name]; } } function getFunctionNames(functionDeclaration) { switch (functionDeclaration.kind) { case 262 /* FunctionDeclaration */: - if (functionDeclaration.name) - return [functionDeclaration.name]; + if (functionDeclaration.name) return [functionDeclaration.name]; const defaultModifier = Debug.checkDefined( findModifier(functionDeclaration, 90 /* DefaultKeyword */), "Nameless function declaration should be a default export" @@ -145960,8 +145547,7 @@ function getFunctionNames(functionDeclaration) { case 219 /* ArrowFunction */: return [functionDeclaration.parent.name]; case 218 /* FunctionExpression */: - if (functionDeclaration.name) - return [functionDeclaration.name, functionDeclaration.parent.name]; + if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; default: return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); @@ -146209,8 +145795,7 @@ registerRefactor(refactorName11, { }); function getRefactorActionsToConvertToOptionalChain(context) { const info = getInfo3(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName11, @@ -146246,15 +145831,13 @@ function getInfo3(context, considerEmptySpans = true) { const { file, program } = context; const span = getRefactorContextSpan(context); const forEmptySpan = span.length === 0; - if (forEmptySpan && !considerEmptySpans) - return void 0; + if (forEmptySpan && !considerEmptySpans) return void 0; const startToken = getTokenAtPosition(file, span.start); const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; - if (!expression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + if (!expression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; const checker = program.getTypeChecker(); return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); } @@ -146276,8 +145859,7 @@ function getBinaryInfo(expression) { return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; } const finalExpression = getFinalExpressionInChain(expression.right); - if (!finalExpression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + if (!finalExpression) return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; } @@ -146306,13 +145888,11 @@ function getMatchingStart(chain, subchain) { } function chainStartsWith(chain, subchain) { while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { - if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) - break; + if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) break; chain = chain.expression; } while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { - if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) - return false; + if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) return false; chain = chain.expression; subchain = subchain.expression; } @@ -146373,8 +145953,7 @@ function convertOccurrences(checker, toConvert, occurrences) { const chain = convertOccurrences(checker, toConvert.expression, occurrences); const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); - if (isOccurrence) - occurrences.pop(); + if (isOccurrence) occurrences.pop(); if (isCallExpression(toConvert)) { return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); } else if (isPropertyAccessExpression(toConvert)) { @@ -147330,13 +146909,7 @@ function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParame function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { const checker = context.program.getTypeChecker(); const file = scope.getSourceFile(); - const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( - node.name.text, - node, - 111551 /* Value */, - /*excludeGlobals*/ - false - ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const localNameText = getIdentifierForNode(node, scope, checker, file); const isJS = isInJSFile(scope); let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); let initializer = transformConstantInitializer(skipParentheses(node), substitutions); @@ -147449,16 +147022,12 @@ function extractConstantInScope(node, scope, { substitutions }, rangeFacts, cont ); return { renameFilename, renameLocation, edits }; function transformFunctionInitializerAndType(variableType2, initializer2) { - if (variableType2 === void 0) - return { variableType: variableType2, initializer: initializer2 }; - if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) - return { variableType: variableType2, initializer: initializer2 }; + if (variableType2 === void 0) return { variableType: variableType2, initializer: initializer2 }; + if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) return { variableType: variableType2, initializer: initializer2 }; const functionType = checker.getTypeAtLocation(node); const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); - if (!functionSignature) - return { variableType: variableType2, initializer: initializer2 }; - if (!!functionSignature.getTypeParameters()) - return { variableType: variableType2, initializer: initializer2 }; + if (!functionSignature) return { variableType: variableType2, initializer: initializer2 }; + if (!!functionSignature.getTypeParameters()) return { variableType: variableType2, initializer: initializer2 }; const parameters = []; let hasAny = false; for (const p of initializer2.parameters) { @@ -147466,13 +147035,11 @@ function extractConstantInScope(node, scope, { substitutions }, rangeFacts, cont parameters.push(p); } else { const paramType = checker.getTypeAtLocation(p); - if (paramType === checker.getAnyType()) - hasAny = true; + if (paramType === checker.getAnyType()) hasAny = true; parameters.push(factory.updateParameterDeclaration(p, p.modifiers, p.dotDotDotToken, p.name, p.questionToken, p.type || checker.typeToTypeNode(paramType, scope, 1 /* NoTruncation */), p.initializer)); } } - if (hasAny) - return { variableType: variableType2, initializer: initializer2 }; + if (hasAny) return { variableType: variableType2, initializer: initializer2 }; variableType2 = void 0; if (isArrowFunction(initializer2)) { initializer2 = factory.updateArrowFunction(initializer2, canHaveModifiers(node) ? getModifiers(node) : void 0, initializer2.typeParameters, parameters, initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), initializer2.equalsGreaterThanToken, initializer2.body); @@ -147649,8 +147216,7 @@ function getNodeToInsertPropertyBefore(maxPos, scope) { } prevMember = member; } - if (prevMember === void 0) - return Debug.fail(); + if (prevMember === void 0) return Debug.fail(); return prevMember; } function getNodeToInsertConstantBefore(node, scope) { @@ -148000,13 +147566,11 @@ var generateGetSetAction = { registerRefactor(actionName, { kinds: [generateGetSetAction.kind], getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { - if (!context.endPosition) - return void 0; + if (!context.endPosition) return void 0; const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); - if (!edits) - return void 0; + if (!edits) return void 0; const renameFilename = context.file.fileName; const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; @@ -148020,11 +147584,9 @@ registerRefactor(actionName, { return { renameFilename, renameLocation, edits }; }, getAvailableActions(context) { - if (!context.endPosition) - return emptyArray; + if (!context.endPosition) return emptyArray; const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: actionName, @@ -148069,8 +147631,7 @@ function getRefactorEditsToInferReturnType(context) { } function getRefactorActionsToInferReturnType(context) { const info = getInfo4(context); - if (!info) - return emptyArray; + if (!info) return emptyArray; if (!isRefactorErrorInfo(info)) { return [{ name: refactorName13, @@ -148100,8 +147661,7 @@ function doChange7(sourceFile, changes, declaration, typeNode) { } } function getInfo4(context) { - if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) - return; + if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) return; const token = getTouchingPropertyName(context.file, context.startPosition); const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); if (!declaration || !declaration.body || declaration.type) { @@ -148827,8 +148387,7 @@ function hasJSDocInheritDocTag(node) { return getJSDocTags(node).some((tag) => tag.tagName.text === "inheritDoc" || tag.tagName.text === "inheritdoc"); } function getJsDocTagsOfDeclarations(declarations, checker) { - if (!declarations) - return emptyArray; + if (!declarations) return emptyArray; let tags = ts_JsDoc_exports.getJsDocTagsFromDeclarations(declarations, checker); if (checker && (tags.length === 0 || declarations.some(hasJSDocInheritDocTag))) { const seenSymbols = /* @__PURE__ */ new Set(); @@ -148851,8 +148410,7 @@ function getJsDocTagsOfDeclarations(declarations, checker) { return tags; } function getDocumentationComment(declarations, checker) { - if (!declarations) - return emptyArray; + if (!declarations) return emptyArray; let doc = ts_JsDoc_exports.getJsDocCommentsFromDeclarations(declarations, checker); if (checker && (doc.length === 0 || declarations.some(hasJSDocInheritDocTag))) { const seenSymbols = /* @__PURE__ */ new Set(); @@ -148866,8 +148424,7 @@ function getDocumentationComment(declarations, checker) { return symbol.getDocumentationComment(checker); } }); - if (inheritedDocs) - doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); + if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); } } return doc; @@ -148875,8 +148432,7 @@ function getDocumentationComment(declarations, checker) { function findBaseOfDeclaration(checker, declaration, cb) { var _a; const classOrInterfaceDeclaration = ((_a = declaration.parent) == null ? void 0 : _a.kind) === 176 /* Constructor */ ? declaration.parent.parent : declaration.parent; - if (!classOrInterfaceDeclaration) - return; + if (!classOrInterfaceDeclaration) return; const isStaticMember = hasStaticModifier(declaration); return firstDefined(getAllSuperTypeNodes(classOrInterfaceDeclaration), (superTypeNode) => { const baseType = checker.getTypeAtLocation(superTypeNode); @@ -149255,7 +148811,8 @@ var invalidOperationsInPartialSemanticMode = [ "provideCallHierarchyIncomingCalls", "provideCallHierarchyOutgoingCalls", "provideInlayHints", - "getSupportedCodeFixes" + "getSupportedCodeFixes", + "getPasteEdits" ]; var invalidOperationsInSyntacticMode = [ ...invalidOperationsInPartialSemanticMode, @@ -149276,7 +148833,7 @@ var invalidOperationsInSyntacticMode = [ "findRenameLocations", "getApplicableRefactors" ]; -function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()), syntaxOnlyOrLanguageServiceMode) { +function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory(), host.jsDocParsingMode), syntaxOnlyOrLanguageServiceMode) { var _a; let languageServiceMode; if (syntaxOnlyOrLanguageServiceMode === void 0) { @@ -149437,16 +148994,14 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h function getParsedCommandLine(fileName) { const path = toPath(fileName, currentDirectory, getCanonicalFileName); const existing = parsedCommandLines == null ? void 0 : parsedCommandLines.get(path); - if (existing !== void 0) - return existing || void 0; + if (existing !== void 0) return existing || void 0; const result = host.getParsedCommandLine ? host.getParsedCommandLine(fileName) : getParsedCommandLineOfConfigFileUsingSourceFile(fileName); (parsedCommandLines || (parsedCommandLines = /* @__PURE__ */ new Map())).set(path, result || false); return result; } function getParsedCommandLineOfConfigFileUsingSourceFile(configFileName) { const result = getOrCreateSourceFile(configFileName, 100 /* JSON */); - if (!result) - return void 0; + if (!result) return void 0; result.path = toPath(configFileName, currentDirectory, getCanonicalFileName); result.resolvedPath = result.path; result.originalFileName = result.fileName; @@ -149511,8 +149066,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h function updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans) { const checker = program.getTypeChecker(); const symbol = getSymbolForProgram(); - if (!symbol) - return false; + if (!symbol) return false; for (const referencedSymbol of referencedSymbols) { for (const ref of referencedSymbol.references) { const refNode = getNodeForSpan(ref); @@ -149551,8 +149105,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } function getNodeForSpan(docSpan) { const sourceFile = program.getSourceFile(docSpan.fileName); - if (!sourceFile) - return void 0; + if (!sourceFile) return void 0; const rawNode = getTouchingPropertyName(sourceFile, docSpan.textSpan.start); const adjustedNode = ts_FindAllReferences_exports.Core.getAdjustedNode(rawNode, { use: ts_FindAllReferences_exports.FindReferencesUse.References }); return adjustedNode; @@ -149663,6 +149216,19 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h tags }; } + function getPasteEdits(args, formatOptions) { + synchronizeHostData(); + return ts_PasteEdits_exports.pasteEditsProvider( + getValidSourceFile(args.targetFile), + args.pastedText, + args.pasteLocations, + args.copiedFrom ? { file: getValidSourceFile(args.copiedFrom.file), range: args.copiedFrom.range } : void 0, + host, + args.preferences, + ts_formatting_exports.getFormatContext(formatOptions, host), + cancellationToken + ); + } function getNodeForQuickInfo(node) { if (isNewExpression(node.parent) && node.pos === node.parent.pos) { return node.parent.expression; @@ -149727,8 +149293,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); - if (!ts_Rename_exports.nodeIsEligibleForRename(node)) - return void 0; + if (!ts_Rename_exports.nodeIsEligibleForRename(node)) return void 0; if (isIdentifier(node) && (isJsxOpeningElement(node.parent) || isJsxClosingElement(node.parent)) && isIntrinsicJsxName(node.escapedText)) { const { openingElement, closingElement } = node.parent.parent; return [openingElement, closingElement].map((node2) => { @@ -149904,22 +149469,22 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes66, formatOptions, preferences = emptyOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes67, formatOptions, preferences = emptyOptions) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const span = createTextSpanFromBounds(start, end); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return flatMap(deduplicate(errorCodes66, equateValues, compareValues), (errorCode) => { + return flatMap(deduplicate(errorCodes67, equateValues, compareValues), (errorCode) => { cancellationToken.throwIfCancellationRequested(); return ts_codefix_exports.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences }); }); } - function getCombinedCodeFix(scope, fixId53, formatOptions, preferences = emptyOptions) { + function getCombinedCodeFix(scope, fixId55, formatOptions, preferences = emptyOptions) { synchronizeHostData(); Debug.assert(scope.type === "file"); const sourceFile = getValidSourceFile(scope.fileName); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return ts_codefix_exports.getAllFixes({ fixId: fixId53, sourceFile, program, host, cancellationToken, formatContext, preferences }); + return ts_codefix_exports.getAllFixes({ fixId: fixId55, sourceFile, program, host, cancellationToken, formatContext, preferences }); } function organizeImports2(args, formatOptions, preferences = emptyOptions) { synchronizeHostData(); @@ -149970,8 +149535,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h function getJsxClosingTagAtPosition(fileName, position) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const token = findPrecedingToken(position, sourceFile); - if (!token) - return void 0; + if (!token) return void 0; const element = token.kind === 32 /* GreaterThanToken */ && isJsxOpeningElement(token.parent) ? token.parent.parent : isJsxText(token) && isJsxElement(token.parent) ? token.parent : void 0; if (element && isUnclosedTag(element)) { return { newText: `` }; @@ -149984,18 +149548,15 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h function getLinkedEditingRangeAtPosition(fileName, position) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); const token = findPrecedingToken(position, sourceFile); - if (!token || token.parent.kind === 307 /* SourceFile */) - return void 0; + if (!token || token.parent.kind === 307 /* SourceFile */) return void 0; const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; if (isJsxFragment(token.parent.parent)) { const openFragment = token.parent.parent.openingFragment; const closeFragment = token.parent.parent.closingFragment; - if (containsParseError(openFragment) || containsParseError(closeFragment)) - return void 0; + if (containsParseError(openFragment) || containsParseError(closeFragment)) return void 0; const openPos = openFragment.getStart(sourceFile) + 1; const closePos = closeFragment.getStart(sourceFile) + 2; - if (position !== openPos && position !== closePos) - return void 0; + if (position !== openPos && position !== closePos) return void 0; return { ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }], wordPattern: jsxTagWordPattern @@ -150007,8 +149568,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } return false; }); - if (!tag) - return void 0; + if (!tag) return void 0; Debug.assert(isJsxOpeningElement(tag) || isJsxClosingElement(tag), "tag should be opening or closing element"); const openTag = tag.parent.openingElement; const closeTag = tag.parent.closingElement; @@ -150016,13 +149576,10 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const openTagNameEnd = openTag.tagName.end; const closeTagNameStart = closeTag.tagName.getStart(sourceFile); const closeTagNameEnd = closeTag.tagName.end; - if (openTagNameStart === openTag.getStart(sourceFile) || closeTagNameStart === closeTag.getStart(sourceFile) || openTagNameEnd === openTag.getEnd() || closeTagNameEnd === closeTag.getEnd()) - return void 0; - if (!(openTagNameStart <= position && position <= openTagNameEnd || closeTagNameStart <= position && position <= closeTagNameEnd)) - return void 0; + if (openTagNameStart === openTag.getStart(sourceFile) || closeTagNameStart === closeTag.getStart(sourceFile) || openTagNameEnd === openTag.getEnd() || closeTagNameEnd === closeTag.getEnd()) return void 0; + if (!(openTagNameStart <= position && position <= openTagNameEnd || closeTagNameStart <= position && position <= closeTagNameEnd)) return void 0; const openingTagText = openTag.tagName.getText(sourceFile); - if (openingTagText !== closeTag.tagName.getText(sourceFile)) - return void 0; + if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; return { ranges: [{ start: openTagNameStart, length: openTagNameEnd - openTagNameStart }, { start: closeTagNameStart, length: closeTagNameEnd - closeTagNameStart }], wordPattern: jsxTagWordPattern @@ -150262,8 +149819,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h descriptor = descriptors[i]; } } - if (descriptor === void 0) - return Debug.fail(); + if (descriptor === void 0) return Debug.fail(); if (isLetterOrDigit(fileContents.charCodeAt(matchPosition + descriptor.text.length))) { continue; } @@ -150379,6 +149935,16 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const sourceFile = getValidSourceFile(fileName); return ts_InlayHints_exports.provideInlayHints(getInlayHintsContext(sourceFile, span, preferences)); } + function mapCode2(sourceFile, contents, focusLocations, formatOptions, preferences) { + return ts_MapCode_exports.mapCode( + syntaxTreeCache.getCurrentSourceFile(sourceFile), + contents, + focusLocations, + host, + ts_formatting_exports.getFormatContext(formatOptions, host), + preferences + ); + } const ls = { dispose, cleanupSemanticCache, @@ -150448,7 +150014,9 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h commentSelection, uncommentSelection, provideInlayHints: provideInlayHints2, - getSupportedCodeFixes + getSupportedCodeFixes, + getPasteEdits, + mapCode: mapCode2 }; switch (languageServiceMode) { case 0 /* Semantic */: @@ -150535,8 +150103,7 @@ function getSymbolAtLocationForQuickInfo(node, checker) { } function getPropertySymbolsFromContextualType(node, checker, contextualType, unionSymbolOk) { const name = getNameFromPropertyName(node.name); - if (!name) - return emptyArray; + if (!name) return emptyArray; if (!contextualType.isUnion()) { const symbol = contextualType.getProperty(name); return symbol ? [symbol] : emptyArray; @@ -150545,8 +150112,7 @@ function getPropertySymbolsFromContextualType(node, checker, contextualType, uni const discriminatedPropertySymbols = mapDefined(filteredTypes, (t) => t.getProperty(name)); if (unionSymbolOk && (discriminatedPropertySymbols.length === 0 || discriminatedPropertySymbols.length === contextualType.types.length)) { const symbol = contextualType.getProperty(name); - if (symbol) - return [symbol]; + if (symbol) return [symbol]; } if (!filteredTypes.length && !discriminatedPropertySymbols.length) { return mapDefined(contextualType.types, (t) => t.getProperty(name)); @@ -150629,10 +150195,8 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (index >= 0) { let start = index; let end = index + 1; - while (start > 0 && match(nodeArray[start - 1])) - start--; - while (end < nodeArray.length && match(nodeArray[end])) - end++; + while (start > 0 && match(nodeArray[start - 1])) start--; + while (end < nodeArray.length && match(nodeArray[end])) end++; return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray[start].pos), nodeArray[end - 1].end); } } @@ -151096,12 +150660,9 @@ function isValidCallHierarchyDeclaration(node) { return isSourceFile(node) || isModuleDeclaration(node) && isIdentifier(node.name) || isFunctionDeclaration(node) || isClassDeclaration(node) || isClassStaticBlockDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isGetAccessorDeclaration(node) || isSetAccessorDeclaration(node) || isNamedExpression(node) || isAssignedExpression(node); } function getCallHierarchyDeclarationReferenceNode(node) { - if (isSourceFile(node)) - return node; - if (isNamedDeclaration(node)) - return node.name; - if (isAssignedExpression(node)) - return node.parent.name; + if (isSourceFile(node)) return node; + if (isNamedDeclaration(node)) return node.name; + if (isAssignedExpression(node)) return node.parent.name; return Debug.checkDefined(node.modifiers && find(node.modifiers, isDefaultModifier3)); } function isDefaultModifier3(node) { @@ -151366,8 +150927,7 @@ function createCallSiteCollector(program, callSites) { } } function collect(node) { - if (!node) - return; + if (!node) return; if (node.flags & 33554432 /* Ambient */) { return; } @@ -151574,8 +151134,6 @@ __export(ts_codefix_exports, { getSupportedErrorCodes: () => getSupportedErrorCodes, importFixName: () => importFixName, importSymbols: () => importSymbols, - moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier, - moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier, parameterShouldGetTypeFromJSDoc: () => parameterShouldGetTypeFromJSDoc, registerCodeFix: () => registerCodeFix, setJsonCompilerOptionValue: () => setJsonCompilerOptionValue, @@ -151598,14 +151156,14 @@ function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { void 0 ); } -function createCodeFixAction(fixName8, changes, description3, fixId53, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId53, diagnosticToString(fixAllDescription), command); +function createCodeFixAction(fixName8, changes, description3, fixId55, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId55, diagnosticToString(fixAllDescription), command); } -function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId53, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId53, fixAllDescription && diagnosticToString(fixAllDescription), command); +function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId55, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId55, fixAllDescription && diagnosticToString(fixAllDescription), command); } -function createCodeFixActionWorker(fixName8, description3, changes, fixId53, fixAllDescription, command) { - return { fixName: fixName8, description: description3, changes, fixId: fixId53, fixAllDescription, commands: command ? [command] : void 0 }; +function createCodeFixActionWorker(fixName8, description3, changes, fixId55, fixAllDescription, command) { + return { fixName: fixName8, description: description3, changes, fixId: fixId55, fixAllDescription, commands: command ? [command] : void 0 }; } function registerCodeFix(reg) { for (const error2 of reg.errorCodes) { @@ -151613,9 +151171,9 @@ function registerCodeFix(reg) { errorCodeToFixes.add(String(error2), reg); } if (reg.fixIds) { - for (const fixId53 of reg.fixIds) { - Debug.assert(!fixIdToRegistration.has(fixId53)); - fixIdToRegistration.set(fixId53, reg); + for (const fixId55 of reg.fixIds) { + Debug.assert(!fixIdToRegistration.has(fixId55)); + fixIdToRegistration.set(fixId55, reg); } } } @@ -151624,17 +151182,15 @@ function getSupportedErrorCodes() { return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys())); } function removeFixIdIfFixAllUnavailable(registration, diagnostics) { - const { errorCodes: errorCodes66 } = registration; + const { errorCodes: errorCodes67 } = registration; let maybeFixableDiagnostics = 0; for (const diag2 of diagnostics) { - if (contains(errorCodes66, diag2.code)) - maybeFixableDiagnostics++; - if (maybeFixableDiagnostics > 1) - break; + if (contains(errorCodes67, diag2.code)) maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) break; } const fixAllUnavailable = maybeFixableDiagnostics < 2; - return ({ fixId: fixId53, fixAllDescription, ...action }) => { - return fixAllUnavailable ? action : { ...action, fixId: fixId53, fixAllDescription }; + return ({ fixId: fixId55, fixAllDescription, ...action }) => { + return fixAllUnavailable ? action : { ...action, fixId: fixId55, fixAllDescription }; }; } function getFixes(context) { @@ -151651,24 +151207,30 @@ function createCombinedCodeActions(changes, commands) { function createFileTextChanges(fileName, textChanges2) { return { fileName, textChanges: textChanges2 }; } -function codeFixAll(context, errorCodes66, use) { +function codeFixAll(context, errorCodes67, use) { const commands = []; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes66, (diag2) => use(t, diag2, commands))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes67, (diag2) => use(t, diag2, commands))); return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands); } -function eachDiagnostic(context, errorCodes66, cb) { +function eachDiagnostic(context, errorCodes67, cb) { for (const diag2 of getDiagnostics(context)) { - if (contains(errorCodes66, diag2.code)) { + if (contains(errorCodes67, diag2.code)) { cb(diag2); } } } function getDiagnostics({ program, sourceFile, cancellationToken }) { - return [ + const diagnostics = [ ...program.getSemanticDiagnostics(sourceFile, cancellationToken), ...program.getSyntacticDiagnostics(sourceFile, cancellationToken), ...computeSuggestionDiagnostics(sourceFile, program, cancellationToken) ]; + if (getEmitDeclarations(program.getCompilerOptions())) { + diagnostics.push( + ...program.getDeclarationDiagnostics(sourceFile, cancellationToken) + ); + } + return diagnostics; } // src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts @@ -151678,8 +151240,7 @@ registerCodeFix({ errorCodes, getCodeActions: function getCodeActionsToAddConvertToUnknownForNonOverlappingTypes(context) { const assertion = getAssertion(context.sourceFile, context.span.start); - if (assertion === void 0) - return void 0; + if (assertion === void 0) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange(t, context.sourceFile, assertion)); return [createCodeFixAction(fixId, changes, Diagnostics.Add_unknown_conversion_for_non_overlapping_types, fixId, Diagnostics.Add_unknown_to_all_conversions_of_non_overlapping_types)]; }, @@ -151696,8 +151257,7 @@ function makeChange(changeTracker, sourceFile, assertion) { changeTracker.replaceNode(sourceFile, assertion.expression, replacement); } function getAssertion(sourceFile, pos) { - if (isInJSFile(sourceFile)) - return void 0; + if (isInJSFile(sourceFile)) return void 0; return findAncestor(getTokenAtPosition(sourceFile, pos), (n) => isAsExpression(n) || isTypeAssertionExpression(n)); } @@ -151787,8 +151347,7 @@ function makeChange2(changeTracker, sourceFile, insertionSite, fixedDeclarations ); } function getFixableErrorSpanDeclaration(sourceFile, span) { - if (!span) - return void 0; + if (!span) return void 0; const token = getTokenAtPosition(sourceFile, span.start); const decl = findAncestor(token, (node) => { if (node.getStart(sourceFile) < span.start || node.getEnd() > textSpanEnd(span)) { @@ -152047,8 +151606,7 @@ registerCodeFix({ function makeChange4(changeTracker, sourceFile, pos, program, fixedNodes) { const token = getTokenAtPosition(sourceFile, pos); const forInitializer = findAncestor(token, (node) => isForInOrOfStatement(node.parent) ? node.parent.initializer === node : isPossiblyPartOfDestructuring(node) ? false : "quit"); - if (forInitializer) - return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); + if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); const parent2 = token.parent; if (isBinaryExpression(parent2) && parent2.operatorToken.kind === 64 /* EqualsToken */ && isExpressionStatement(parent2.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); @@ -152267,24 +151825,18 @@ function getSourceTarget(errorNode, checker) { return { source: errorNode.parent.initializer, target: errorNode.parent.name }; } else if (isCallExpression(errorNode.parent)) { const n = checker.getSymbolAtLocation(errorNode.parent.expression); - if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind)) - return void 0; - if (!isExpression(errorNode)) - return void 0; + if (!(n == null ? void 0 : n.valueDeclaration) || !isFunctionLikeKind(n.valueDeclaration.kind)) return void 0; + if (!isExpression(errorNode)) return void 0; const i = errorNode.parent.arguments.indexOf(errorNode); - if (i === -1) - return void 0; + if (i === -1) return void 0; const name = n.valueDeclaration.parameters[i].name; - if (isIdentifier(name)) - return { source: errorNode, target: name }; + if (isIdentifier(name)) return { source: errorNode, target: name }; } else if (isPropertyAssignment(errorNode.parent) && isIdentifier(errorNode.parent.name) || isShorthandPropertyAssignment(errorNode.parent)) { const parentTarget = getSourceTarget(errorNode.parent.parent, checker); - if (!parentTarget) - return void 0; + if (!parentTarget) return void 0; const prop = checker.getPropertyOfType(checker.getTypeAtLocation(parentTarget.target), errorNode.parent.name.text); const declaration = (_a = prop == null ? void 0 : prop.declarations) == null ? void 0 : _a[0]; - if (!declaration) - return void 0; + if (!declaration) return void 0; return { source: isPropertyAssignment(errorNode.parent) ? errorNode.parent.initializer : errorNode.parent.name, target: declaration @@ -152312,16 +151864,14 @@ registerCodeFix({ errorCodes: errorCodes9, getCodeActions(context) { const decl = getDeclaration(context.sourceFile, context.span.start); - if (!decl) - return; + if (!decl) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl)); return [createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId8], getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => { const decl = getDeclaration(diag2.file, diag2.start); - if (decl) - doChange8(changes, diag2.file, decl); + if (decl) doChange8(changes, diag2.file, decl); }) }); function getDeclaration(file, pos) { @@ -152338,25 +151888,20 @@ function doChange8(changes, sourceFile, decl) { if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) { if (!decl.typeParameters) { const typeParameters = getJSDocTypeParameterDeclarations(decl); - if (typeParameters.length) - changes.insertTypeParameters(sourceFile, decl, typeParameters); + if (typeParameters.length) changes.insertTypeParameters(sourceFile, decl, typeParameters); } const needParens = isArrowFunction(decl) && !findChildOfKind(decl, 21 /* OpenParenToken */, sourceFile); - if (needParens) - changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(21 /* OpenParenToken */)); + if (needParens) changes.insertNodeBefore(sourceFile, first(decl.parameters), factory.createToken(21 /* OpenParenToken */)); for (const param of decl.parameters) { if (!param.type) { const paramType = getJSDocType(param); - if (paramType) - changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode)); + if (paramType) changes.tryInsertTypeAnnotation(sourceFile, param, visitNode(paramType, transformJSDocType, isTypeNode)); } } - if (needParens) - changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(22 /* CloseParenToken */)); + if (needParens) changes.insertNodeAfter(sourceFile, last(decl.parameters), factory.createToken(22 /* CloseParenToken */)); if (!decl.type) { const returnType = getJSDocReturnType(decl); - if (returnType) - changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode)); + if (returnType) changes.tryInsertTypeAnnotation(sourceFile, decl, visitNode(returnType, transformJSDocType, isTypeNode)); } } else { const jsdocType = Debug.checkDefined(getJSDocType(decl), "A JSDocType for this declaration should exist"); @@ -152555,17 +152100,13 @@ function doChange9(changes, sourceFile, position, checker, preferences, compiler return memberElements; function shouldConvertDeclaration(_target, source) { if (isAccessExpression(_target)) { - if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target)) - return true; + if (isPropertyAccessExpression(_target) && isConstructorAssignment(_target)) return true; return isFunctionLike(source); } else { return every(_target.properties, (property) => { - if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) - return true; - if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) - return true; - if (isConstructorAssignment(property)) - return true; + if (isMethodDeclaration(property) || isGetOrSetAccessorDeclaration(property)) return true; + if (isPropertyAssignment(property) && isFunctionExpression(property.initializer) && !!property.name) return true; + if (isConstructorAssignment(property)) return true; return false; }); } @@ -152621,17 +152162,14 @@ function doChange9(changes, sourceFile, position, checker, preferences, compiler if (isPropertyAssignment(property) && isFunctionExpression(property.initializer)) { createFunctionLikeExpressionMember(members, property.initializer, property.name); } - if (isConstructorAssignment(property)) - return; + if (isConstructorAssignment(property)) return; return; } ); return; } else { - if (isSourceFileJS(sourceFile)) - return; - if (!isPropertyAccessExpression(memberDeclaration)) - return; + if (isSourceFileJS(sourceFile)) return; + if (!isPropertyAccessExpression(memberDeclaration)) return; const prop = factory.createPropertyDeclaration( modifiers, memberDeclaration.name, @@ -152646,10 +152184,8 @@ function doChange9(changes, sourceFile, position, checker, preferences, compiler return; } function createFunctionLikeExpressionMember(members2, expression, name) { - if (isFunctionExpression(expression)) - return createFunctionExpressionMember(members2, expression, name); - else - return createArrowFunctionExpressionMember(members2, expression, name); + if (isFunctionExpression(expression)) return createFunctionExpressionMember(members2, expression, name); + else return createArrowFunctionExpressionMember(members2, expression, name); } function createFunctionExpressionMember(members2, functionExpression, name) { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, 134 /* AsyncKeyword */)); @@ -152752,10 +152288,8 @@ function getModifierKindFromSource(source, kind) { return canHaveModifiers(source) ? filter(source.modifiers, (modifier) => modifier.kind === kind) : void 0; } function isConstructorAssignment(x) { - if (!x.name) - return false; - if (isIdentifier(x.name) && x.name.text === "constructor") - return true; + if (!x.name) return false; + if (isIdentifier(x.name) && x.name.text === "constructor") return true; return false; } function tryGetPropertyName(node, compilerOptions, quotePreference) { @@ -152840,8 +152374,7 @@ function convertToAsyncFunction(changes, sourceFile, position, checker) { function getReturnStatementsWithPromiseHandlers(body, checker) { const res = []; forEachReturnStatement(body, (ret) => { - if (isReturnStatementWithFixablePromiseHandler(ret, checker)) - res.push(ret); + if (isReturnStatementWithFixablePromiseHandler(ret, checker)) res.push(ret); }); return res; } @@ -152866,8 +152399,7 @@ function getAllPromiseExpressionsToReturn(func, checker) { return setOfExpressionsToReturn; } function isPromiseReturningCallExpression(node, checker, name) { - if (!isCallExpression(node)) - return false; + if (!isCallExpression(node)) return false; const isExpressionOfName = hasPropertyAccessExpressionWithName(node, name); const nodeType = isExpressionOfName && checker.getTypeAtLocation(node); return !!(nodeType && checker.getPromisedTypeOfPromise(nodeType)); @@ -152893,8 +152425,7 @@ function getExplicitPromisedTypeOfPromiseReturningCallExpression(node, callback, } } function isPromiseTypedExpression(node, checker) { - if (!isExpression(node)) - return false; + if (!isExpression(node)) return false; return !!checker.getPromisedTypeOfPromise(checker.getTypeAtLocation(node)); } function renameCollidingVarNames(nodeToRename, checker, synthNamesMap) { @@ -152991,8 +152522,7 @@ function transformExpression(returnContextNode, node, transformer, hasContinuati return silentFail(); } function isNullOrUndefined2({ checker }, node) { - if (node.kind === 106 /* NullKeyword */) - return true; + if (node.kind === 106 /* NullKeyword */) return true; if (isIdentifier(node) && !isGeneratedIdentifier(node) && idText(node) === "undefined") { const symbol = checker.getSymbolAtLocation(node); return !symbol || checker.isUndefinedSymbol(symbol); @@ -153088,8 +152618,7 @@ function transformFinally(node, onFinally, transformer, hasContinuation, continu true, possibleNameForVarDecl ); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const inlinedCallback = transformCallbackArgument( onFinally, hasContinuation, @@ -153100,8 +152629,7 @@ function transformFinally(node, onFinally, transformer, hasContinuation, continu node, transformer ); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const tryBlock = factory.createBlock(inlinedLeftHandSide); const finallyBlock = factory.createBlock(inlinedCallback); const tryStatement = factory.createTryStatement( @@ -153134,11 +152662,9 @@ function transformCatch(node, onRejected, transformer, hasContinuation, continua true, possibleNameForVarDecl ); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const inlinedCallback = transformCallbackArgument(onRejected, hasContinuation, possibleNameForVarDecl, inputArgName, node, transformer); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const tryBlock = factory.createBlock(inlinedLeftHandSide); const catchClause = factory.createCatchClause(inputArgName && getSynthesizedDeepClone(declareSynthBindingName(inputArgName)), factory.createBlock(inlinedCallback)); const tryStatement = factory.createTryStatement( @@ -153165,11 +152691,9 @@ function transformThen(node, onFulfilled, onRejected, transformer, hasContinuati true, inputArgName ); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); const inlinedCallback = transformCallbackArgument(onFulfilled, hasContinuation, continuationArgName, inputArgName, node, transformer); - if (hasFailed()) - return silentFail(); + if (hasFailed()) return silentFail(); return concatenate(inlinedLeftHandSide, inlinedCallback); } function transformPromiseExpressionOfPropertyAccess(returnContextNode, node, transformer, hasContinuation, continuationArgName) { @@ -153395,11 +152919,9 @@ function getArgBindingName(funcNode, transformer) { } return name; function getMappedBindingNameOrDefault(bindingName) { - if (isIdentifier(bindingName)) - return getMapEntryOrDefault(bindingName); + if (isIdentifier(bindingName)) return getMapEntryOrDefault(bindingName); const elements = flatMap(bindingName.elements, (element) => { - if (isOmittedExpression(element)) - return []; + if (isOmittedExpression(element)) return []; return [getMappedBindingNameOrDefault(element.name)]; }); return createSynthBindingPattern(bindingName, elements); @@ -153482,7 +153004,7 @@ registerCodeFix({ function fixImportOfModuleExports(importingFile, exportingFile, program, changes, quotePreference) { var _a; for (const moduleSpecifier of importingFile.imports) { - const imported = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier)) == null ? void 0 : _a.resolvedModule; + const imported = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, importingFile)) == null ? void 0 : _a.resolvedModule; if (!imported || imported.resolvedFileName !== exportingFile.fileName) { continue; } @@ -153759,11 +153281,9 @@ function convertExportsPropertyAssignment({ left, right, parent: parent2 }, sour const name = left.name.text; if ((isFunctionExpression(right) || isArrowFunction(right) || isClassExpression(right)) && (!right.name || right.name.text === name)) { changes.replaceRange(sourceFile, { pos: left.getStart(sourceFile), end: right.getStart(sourceFile) }, factory.createToken(95 /* ExportKeyword */), { suffix: " " }); - if (!right.name) - changes.insertName(sourceFile, right, name); + if (!right.name) changes.insertName(sourceFile, right, name); const semi = findChildOfKind(parent2, 27 /* SemicolonToken */, sourceFile); - if (semi) - changes.delete(sourceFile, semi); + if (semi) changes.delete(sourceFile, semi); } else { changes.replaceNodeRangeWithNodes(sourceFile, left.expression, findChildOfKind(left, 25 /* DotToken */, sourceFile), [factory.createToken(95 /* ExportKeyword */), factory.createToken(87 /* ConstKeyword */)], { joiner: " ", suffix: " " }); } @@ -153905,8 +153425,7 @@ function collectFreeIdentifiers(file) { return map2; } function forEachFreeIdentifier(node, cb) { - if (isIdentifier(node) && isFreeIdentifier(node)) - cb(node); + if (isIdentifier(node) && isFreeIdentifier(node)) cb(node); node.forEachChild((child) => forEachFreeIdentifier(child, cb)); } function isFreeIdentifier(node) { @@ -154005,8 +153524,7 @@ registerCodeFix({ errorCodes: errorCodes12, getCodeActions(context) { const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); - if (!qualifiedName) - return void 0; + if (!qualifiedName) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName)); const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; return [createCodeFixAction(fixId11, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types)]; @@ -154292,8 +153810,7 @@ registerCodeFix({ context.sourceFile, context.span.start ); - if (!node) - return; + if (!node) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile, newLineCharacter)); if (changes.length > 0) { return [ @@ -154314,17 +153831,14 @@ registerCodeFix({ const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition(diag2.file, diag2.start); const fixAll = true; - if (node) - doChange12(changes, node, diag2.file, newLineCharacter, fixAll); + if (node) doChange12(changes, node, diag2.file, newLineCharacter, fixAll); } ) }); function doChange12(changes, node, sourceFile, newLine, fixAll = false) { - if (!isJSDocTypedefTag(node)) - return; + if (!isJSDocTypedefTag(node)) return; const declaration = createDeclaration(node); - if (!declaration) - return; + if (!declaration) return; const commentNode = node.parent; const { leftSibling, rightSibling } = getLeftAndRightSiblings(node); let pos = commentNode.getStart(); @@ -154377,11 +153891,9 @@ function findEndOfTextBetween(jsDocComment, from, to) { function createDeclaration(tag) { var _a; const { typeExpression } = tag; - if (!typeExpression) - return; + if (!typeExpression) return; const typeName = (_a = tag.name) == null ? void 0 : _a.getText(); - if (!typeName) - return; + if (!typeName) return; if (typeExpression.kind === 322 /* JSDocTypeLiteral */) { return createInterfaceForTypeLiteral(typeName, typeExpression); } @@ -154391,8 +153903,7 @@ function createDeclaration(tag) { } function createInterfaceForTypeLiteral(typeName, typeLiteral) { const propertySignatures = createSignatureFromTypeLiteral(typeLiteral); - if (!some(propertySignatures)) - return; + if (!some(propertySignatures)) return; return factory.createInterfaceDeclaration( /*modifiers*/ void 0, @@ -154406,8 +153917,7 @@ function createInterfaceForTypeLiteral(typeName, typeLiteral) { } function createTypeAliasForTypeExpression(typeName, typeExpression) { const typeReference = getSynthesizedDeepClone(typeExpression.type); - if (!typeReference) - return; + if (!typeReference) return; return factory.createTypeAliasDeclaration( /*modifiers*/ void 0, @@ -154419,8 +153929,7 @@ function createTypeAliasForTypeExpression(typeName, typeExpression) { } function createSignatureFromTypeLiteral(typeLiteral) { const propertyTags = typeLiteral.jsDocPropertyTags; - if (!some(propertyTags)) - return; + if (!some(propertyTags)) return; const getSignature = (tag) => { var _a; const name = getPropertyName(tag); @@ -154594,8 +154103,7 @@ function addMissingDeclarations(context, implementedTypeNode, sourceFile, classD } function getHeritageClauseSymbolTable(classDeclaration, checker) { const heritageClauseNode = getEffectiveBaseTypeNode(classDeclaration); - if (!heritageClauseNode) - return createSymbolTable(); + if (!heritageClauseNode) return createSymbolTable(); const heritageClauseType = checker.getTypeAtLocation(heritageClauseNode); const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); return createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); @@ -154636,8 +154144,7 @@ registerCodeFix({ /*useAutoImportProvider*/ true ); - if (!info) - return void 0; + if (!info) return void 0; return info.map( ({ fix, symbolName: symbolName2, errorIdentifierText }) => codeActionForFix( context, @@ -154692,14 +154199,12 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre } function addImportForUnresolvedIdentifier(context, symbolToken, useAutoImportProvider2) { const info = getFixInfosWithoutDiagnostic(context, symbolToken, useAutoImportProvider2); - if (!info || !info.length) - return; + if (!info || !info.length) return; addImport(first(info)); } function addImportFromDiagnostic(diagnostic, context) { const info = getFixInfos(context, diagnostic.code, diagnostic.start, useAutoImportProvider); - if (!info || !info.length) - return; + if (!info || !info.length) return; addImport(first(info)); } function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite, referenceImport) { @@ -154785,6 +154290,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre ); const fix = { kind: 3 /* AddNew */, + moduleSpecifierKind: "relative", moduleSpecifier, importKind, addAsTypeOnly, @@ -154841,6 +154347,14 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); break; case 3 /* CommonJS */: + if (compilerOptions.verbatimModuleSyntax) { + const prevValue2 = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); + entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue2, addAsTypeOnly)); + } else { + Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); + entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly }; + } + break; case 2 /* Namespace */: Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly }; @@ -154876,8 +154390,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre useRequire }; if (importKind === 1 /* Default */ && addAsTypeOnly === 2 /* Required */) { - if (typeOnlyEntry) - return typeOnlyEntry; + if (typeOnlyEntry) return typeOnlyEntry; newImports.set(typeOnlyKey, newEntry); return newEntry; } @@ -155023,8 +154536,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre } } function getCombinedVerbatimImports() { - if (!verbatimImports.size) - return void 0; + if (!verbatimImports.size) return void 0; const importDeclarations = new Set(mapDefined([...verbatimImports], (d) => findAncestor(d, isImportDeclaration))); const requireStatements = new Set(mapDefined([...verbatimImports], (d) => findAncestor(d, isRequireVariableStatement))); return [ @@ -155121,7 +154633,7 @@ function createImportSpecifierResolver(importingFile, program, host, preferences importMap, fromCacheOnly ); - const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host); + const result = getBestFix(fixes, importingFile, program, packageJsonImportFilter, host, preferences); return result && { ...result, computedWithoutCacheCount }; } } @@ -155168,7 +154680,7 @@ function getPromoteTypeOnlyCompletionAction(sourceFile, symbolToken, program, ho } function getImportFixForSymbol(sourceFile, exportInfos, program, position, isValidTypeOnlyUseSite, useRequire, host, preferences) { const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); - return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); + return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host, preferences); } function codeFixActionToCodeAction({ description: description3, changes, commands }) { return { description: description3, changes, commands }; @@ -155183,7 +154695,6 @@ function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSym } function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program, host) { var _a, _b; - const compilerOptions = program.getCompilerOptions(); const mainProgramInfo = getInfoWithChecker( program.getTypeChecker(), /*isFromPackageJson*/ @@ -155199,7 +154710,7 @@ function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program true ), `Could not find symbol in specified module for code actions`); function getInfoWithChecker(checker, isFromPackageJson) { - const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker); if (defaultInfo && skipAlias(defaultInfo.symbol, checker) === symbol) { return { symbol: defaultInfo.symbol, moduleSymbol, moduleFileName: void 0, exportKind: defaultInfo.exportKind, targetFlags: skipAlias(symbol, checker).flags, isFromPackageJson }; } @@ -155209,12 +154720,9 @@ function getSingleExportInfoForSymbol(symbol, symbolName2, moduleSymbol, program } } } -function isFutureSymbolExportInfoArray(info) { - return info[0].symbol === void 0; -} function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences, importMap = isFullSourceFile(sourceFile) ? createExistingImportMap(sourceFile, program) : void 0, fromCacheOnly) { const checker = program.getTypeChecker(); - const existingImports = importMap && !isFutureSymbolExportInfoArray(exportInfos) ? flatMap(exportInfos, importMap.getImportsForExportInfo) : emptyArray; + const existingImports = importMap ? flatMap(exportInfos, importMap.getImportsForExportInfo) : emptyArray; const useNamespace = usagePosition !== void 0 && tryUseExistingNamespaceImport(existingImports, usagePosition); const addToExisting = tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker, program.getCompilerOptions()); if (addToExisting) { @@ -155243,12 +154751,11 @@ function getImportFixes(exportInfos, usagePosition, isValidTypeOnlyUseSite, useR function tryUseExistingNamespaceImport(existingImports, position) { return firstDefined(existingImports, ({ declaration, importKind }) => { var _a; - if (importKind !== 0 /* Named */) - return void 0; + if (importKind !== 0 /* Named */) return void 0; const namespacePrefix = getNamespaceLikeImportText(declaration); const moduleSpecifier = namespacePrefix && ((_a = tryGetModuleSpecifierFromDeclaration(declaration)) == null ? void 0 : _a.text); if (moduleSpecifier) { - return { kind: 0 /* UseNamespace */, namespacePrefix, usagePosition: position, moduleSpecifier }; + return { kind: 0 /* UseNamespace */, namespacePrefix, usagePosition: position, moduleSpecifierKind: void 0, moduleSpecifier }; } }); } @@ -155279,8 +154786,7 @@ function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker let best; for (const existingImport of existingImports) { const fix = getAddToExistingImportFix(existingImport); - if (!fix) - continue; + if (!fix) continue; const isTypeOnly = isTypeOnlyImportDeclaration(fix.importClauseOrBindingPattern); if (fix.addAsTypeOnly !== 4 /* NotAllowed */ && isTypeOnly || fix.addAsTypeOnly === 4 /* NotAllowed */ && !isTypeOnly) { return fix; @@ -155293,7 +154799,7 @@ function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker return void 0; } if (declaration.kind === 260 /* VariableDeclaration */) { - return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 206 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: 4 /* NotAllowed */ } : void 0; + return (importKind === 0 /* Named */ || importKind === 1 /* Default */) && declaration.name.kind === 206 /* ObjectBindingPattern */ ? { kind: 2 /* AddToExisting */, importClauseOrBindingPattern: declaration.name, importKind, moduleSpecifierKind: void 0, moduleSpecifier: declaration.initializer.arguments[0].text, addAsTypeOnly: 4 /* NotAllowed */ } : void 0; } const { importClause } = declaration; if (!importClause || !isStringLiteralLike(declaration.moduleSpecifier)) { @@ -155323,6 +154829,7 @@ function tryAddToExistingImport(existingImports, isValidTypeOnlyUseSite, checker kind: 2 /* AddToExisting */, importClauseOrBindingPattern: importClause, importKind, + moduleSpecifierKind: void 0, moduleSpecifier: declaration.moduleSpecifier.text, addAsTypeOnly }; @@ -155348,10 +154855,8 @@ function createExistingImportMap(importingFile, program) { return { getImportsForExportInfo: ({ moduleSymbol, exportKind, targetFlags, symbol }) => { const matchingDeclarations = importMap == null ? void 0 : importMap.get(getSymbolId(moduleSymbol)); - if (!matchingDeclarations) - return emptyArray; - if (isSourceFileJS(importingFile) && !(targetFlags & 111551 /* Value */) && !every(matchingDeclarations, isJSDocImportTag)) - return emptyArray; + if (!matchingDeclarations) return emptyArray; + if (isSourceFileJS(importingFile) && !(targetFlags & 111551 /* Value */) && !every(matchingDeclarations, isJSDocImportTag)) return emptyArray; const importKind = getImportKind(importingFile, exportKind, program); return matchingDeclarations.map((declaration) => ({ declaration, importKind, symbol, targetFlags })); } @@ -155361,25 +154866,18 @@ function shouldUseRequire(sourceFile, program) { if (!hasJSFileExtension(sourceFile.fileName)) { return false; } - if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) - return true; - if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) - return false; + if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true; + if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false; const compilerOptions = program.getCompilerOptions(); if (compilerOptions.configFile) { return getEmitModuleKind(compilerOptions) < 5 /* ES2015 */; } - if (getImpliedNodeFormatForEmit(sourceFile, program) === 1 /* CommonJS */) - return true; - if (getImpliedNodeFormatForEmit(sourceFile, program) === 99 /* ESNext */) - return false; + if (getImpliedNodeFormatForEmit(sourceFile, program) === 1 /* CommonJS */) return true; + if (getImpliedNodeFormatForEmit(sourceFile, program) === 99 /* ESNext */) return false; for (const otherFile of program.getSourceFiles()) { - if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) - continue; - if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) - return true; - if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) - return false; + if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue; + if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true; + if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false; } return true; } @@ -155393,7 +154891,7 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs const getChecker = createGetChecker(program, host); const moduleResolution = getEmitModuleResolutionKind(compilerOptions); const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution); - const getModuleSpecifiers2 = fromCacheOnly ? (exportInfo2) => ({ moduleSpecifiers: ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(exportInfo2.moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false }) : (exportInfo2, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo( + const getModuleSpecifiers2 = fromCacheOnly ? (exportInfo2) => ts_moduleSpecifiers_exports.tryGetModuleSpecifiersFromCache(exportInfo2.moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences) : (exportInfo2, checker) => ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo( exportInfo2.moduleSymbol, checker, compilerOptions, @@ -155408,7 +154906,7 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs let computedWithoutCacheCount = 0; const fixes = flatMap(exportInfo, (exportInfo2, i) => { const checker = getChecker(exportInfo2.isFromPackageJson); - const { computedWithoutCache, moduleSpecifiers } = getModuleSpecifiers2(exportInfo2, checker); + const { computedWithoutCache, moduleSpecifiers, kind: moduleSpecifierKind } = getModuleSpecifiers2(exportInfo2, checker) ?? {}; const importedSymbolHasValueMeaning = !!(exportInfo2.targetFlags & 111551 /* Value */); const addAsTypeOnly = getAddAsTypeOnly( isValidTypeOnlyUseSite, @@ -155421,12 +154919,11 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs ); computedWithoutCacheCount += computedWithoutCache ? 1 : 0; return mapDefined(moduleSpecifiers, (moduleSpecifier) => { - var _a; if (rejectNodeModulesRelativePaths && pathContainsNodeModules(moduleSpecifier)) { return void 0; } if (!importedSymbolHasValueMeaning && isJs && usagePosition !== void 0) { - return { kind: 1 /* JsdocTypeImport */, moduleSpecifier, usagePosition, exportInfo: exportInfo2, isReExport: i > 0 }; + return { kind: 1 /* JsdocTypeImport */, moduleSpecifierKind, moduleSpecifier, usagePosition, exportInfo: exportInfo2, isReExport: i > 0 }; } const importKind = getImportKind(sourceFile, exportInfo2.exportKind, program); let qualification; @@ -155434,7 +154931,14 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs const exportEquals = checker.resolveExternalModuleSymbol(exportInfo2.moduleSymbol); let namespacePrefix; if (exportEquals !== exportInfo2.moduleSymbol) { - namespacePrefix = (_a = getDefaultExportInfoWorker(exportEquals, checker, compilerOptions)) == null ? void 0 : _a.name; + namespacePrefix = forEachNameOfDefaultExport( + exportEquals, + checker, + compilerOptions, + /*preferCapitalizedNames*/ + false, + identity + ); } namespacePrefix || (namespacePrefix = moduleSymbolToValidIdentifier( exportInfo2.moduleSymbol, @@ -155446,6 +154950,7 @@ function getNewImportFixes(program, sourceFile, usagePosition, isValidTypeOnlyUs } return { kind: 3 /* AddNew */, + moduleSpecifierKind, moduleSpecifier, importKind, useRequire, @@ -155475,7 +154980,7 @@ function newImportInfoFromExistingSpecifier({ declaration, importKind, symbol, t checker, compilerOptions ); - return { kind: 3 /* AddNew */, moduleSpecifier, importKind, addAsTypeOnly, useRequire }; + return { kind: 3 /* AddNew */, moduleSpecifierKind: void 0, moduleSpecifier, importKind, addAsTypeOnly, useRequire }; } } function getFixInfos(context, errorCode, pos, useAutoImportProvider) { @@ -155493,20 +154998,19 @@ function getFixInfos(context, errorCode, pos, useAutoImportProvider) { info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); } const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); - return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); + return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host, context.preferences); } -function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host) { +function sortFixInfo(fixes, sourceFile, program, packageJsonImportFilter, host, preferences) { const _toPath = (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)); - return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); + return sort(fixes, (a, b) => compareBooleans(!!a.isJsxNamespaceFix, !!b.isJsxNamespaceFix) || compareValues(a.fix.kind, b.fix.kind) || compareModuleSpecifiers(a.fix, b.fix, sourceFile, program, preferences, packageJsonImportFilter.allowsImportingSpecifier, _toPath)); } function getFixInfosWithoutDiagnostic(context, symbolToken, useAutoImportProvider) { const info = getFixesInfoForNonUMDImport(context, symbolToken, useAutoImportProvider); const packageJsonImportFilter = createPackageJsonImportFilter(context.sourceFile, context.preferences, context.host); - return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host); + return info && sortFixInfo(info, context.sourceFile, context.program, packageJsonImportFilter, context.host, context.preferences); } -function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { - if (!some(fixes)) - return; +function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host, preferences) { + if (!some(fixes)) return; if (fixes[0].kind === 0 /* UseNamespace */ || fixes[0].kind === 2 /* AddToExisting */) { return fixes[0]; } @@ -155518,21 +155022,31 @@ function getBestFix(fixes, sourceFile, program, packageJsonImportFilter, host) { best, sourceFile, program, + preferences, packageJsonImportFilter.allowsImportingSpecifier, (fileName) => toPath(fileName, host.getCurrentDirectory(), hostGetCanonicalFileName(host)) ) === -1 /* LessThan */ ? fix : best ) ); } -function compareModuleSpecifiers(a, b, importingFile, program, allowsImportingSpecifier, toPath3) { +function compareModuleSpecifiers(a, b, importingFile, program, preferences, allowsImportingSpecifier, toPath3) { if (a.kind !== 0 /* UseNamespace */ && b.kind !== 0 /* UseNamespace */) { - return compareBooleans(allowsImportingSpecifier(b.moduleSpecifier), allowsImportingSpecifier(a.moduleSpecifier)) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans( + return compareBooleans( + b.moduleSpecifierKind !== "node_modules" || allowsImportingSpecifier(b.moduleSpecifier), + a.moduleSpecifierKind !== "node_modules" || allowsImportingSpecifier(a.moduleSpecifier) + ) || compareModuleSpecifierRelativity(a, b, preferences) || compareNodeCoreModuleSpecifiers(a.moduleSpecifier, b.moduleSpecifier, importingFile, program) || compareBooleans( isFixPossiblyReExportingImportingFile(a, importingFile.path, toPath3), isFixPossiblyReExportingImportingFile(b, importingFile.path, toPath3) ) || compareNumberOfDirectorySeparators(a.moduleSpecifier, b.moduleSpecifier); } return 0 /* EqualTo */; } +function compareModuleSpecifierRelativity(a, b, preferences) { + if (preferences.importModuleSpecifierPreference === "non-relative" || preferences.importModuleSpecifierPreference === "project-relative") { + return compareBooleans(a.moduleSpecifierKind === "relative", b.moduleSpecifierKind === "relative"); + } + return 0 /* EqualTo */; +} function isFixPossiblyReExportingImportingFile(fix, importingFilePath, toPath3) { var _a; if (fix.isReExport && ((_a = fix.exportInfo) == null ? void 0 : _a.moduleFileName) && isIndexFileName(fix.exportInfo.moduleFileName)) { @@ -155550,17 +155064,14 @@ function isIndexFileName(fileName) { ) === "index"; } function compareNodeCoreModuleSpecifiers(a, b, importingFile, program) { - if (startsWith(a, "node:") && !startsWith(b, "node:")) - return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */; - if (startsWith(b, "node:") && !startsWith(a, "node:")) - return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */; + if (startsWith(a, "node:") && !startsWith(b, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? -1 /* LessThan */ : 1 /* GreaterThan */; + if (startsWith(b, "node:") && !startsWith(a, "node:")) return shouldUseUriStyleNodeCoreModules(importingFile, program) ? 1 /* GreaterThan */ : -1 /* LessThan */; return 0 /* EqualTo */; } function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }, token) { const checker = program.getTypeChecker(); const umdSymbol = getUmdSymbol(token, checker); - if (!umdSymbol) - return void 0; + if (!umdSymbol) return void 0; const symbol = checker.getAliasedSymbol(umdSymbol); const symbolName2 = umdSymbol.name; const exportInfo = [{ symbol: umdSymbol, moduleSymbol: symbol, moduleFileName: void 0, exportKind: 3 /* UMD */, targetFlags: symbol.flags, isFromPackageJson: false }]; @@ -155584,8 +155095,7 @@ function getFixesInfoForUMDImport({ sourceFile, program, host, preferences }, to } function getUmdSymbol(token, checker) { const umdSymbol = isIdentifier(token) ? checker.getSymbolAtLocation(token) : void 0; - if (isUMDExportSymbol(umdSymbol)) - return umdSymbol; + if (isUMDExportSymbol(umdSymbol)) return umdSymbol; const { parent: parent2 } = token; if (isJsxOpeningLikeElement(parent2) && parent2.tagName === token || isJsxOpeningFragment(parent2)) { const parentSymbol = checker.resolveName( @@ -155671,11 +155181,9 @@ function getTypeOnlyPromotionFix(sourceFile, symbolToken, symbolName2, program) /*excludeGlobals*/ true ); - if (!symbol) - return void 0; + if (!symbol) return void 0; const typeOnlyAliasDeclaration = checker.getTypeOnlyAliasDeclaration(symbol); - if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) - return void 0; + if (!typeOnlyAliasDeclaration || getSourceFileOfNode(typeOnlyAliasDeclaration) !== sourceFile) return void 0; return { kind: 4 /* PromoteTypeOnly */, typeOnlyAliasDeclaration }; } function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOptions) { @@ -155696,8 +155204,7 @@ function getSymbolNamesToImport(sourceFile, checker, symbolToken, compilerOption return [symbolToken.text]; } function needsJsxNamespaceFix(jsxNamespace, symbolToken, checker) { - if (isIntrinsicJsxName(symbolToken.text)) - return true; + if (isIntrinsicJsxName(symbolToken.text)) return true; const namespaceSymbol = checker.resolveName( jsxNamespace, symbolToken, @@ -155726,12 +155233,12 @@ function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancella const checker = program2.getTypeChecker(); cancellationToken.throwIfCancellationRequested(); const compilerOptions = program2.getCompilerOptions(); - const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker, compilerOptions); - if (defaultInfo && (defaultInfo.name === symbolName2 || moduleSymbolToValidIdentifier(moduleSymbol, getEmitScriptTarget(compilerOptions), isJsxTagName) === symbolName2) && symbolHasMeaning(defaultInfo.resolvedSymbol, currentTokenMeaning)) { + const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker); + if (defaultInfo && symbolFlagsHaveMeaning(checker.getSymbolFlags(defaultInfo.symbol), currentTokenMeaning) && forEachNameOfDefaultExport(defaultInfo.symbol, checker, compilerOptions, isJsxTagName, (name) => name === symbolName2)) { addSymbol(moduleSymbol, sourceFile, defaultInfo.symbol, defaultInfo.exportKind, program2, isFromPackageJson); } const exportSymbolWithIdenticalName = checker.tryGetMemberInModuleExportsAndProperties(symbolName2, moduleSymbol); - if (exportSymbolWithIdenticalName && symbolHasMeaning(exportSymbolWithIdenticalName, currentTokenMeaning)) { + if (exportSymbolWithIdenticalName && symbolFlagsHaveMeaning(checker.getSymbolFlags(exportSymbolWithIdenticalName), currentTokenMeaning)) { addSymbol(moduleSymbol, sourceFile, exportSymbolWithIdenticalName, 0 /* Named */, program2, isFromPackageJson); } }); @@ -155870,7 +155377,7 @@ function promoteFromTypeOnly(changes, aliasDeclaration, program, sourceFile, pre changes.delete(sourceFile, getTypeKeywordOfTypeOnlyImport(importClause, sourceFile)); if (!compilerOptions.allowImportingTsExtensions) { const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importClause.parent); - const resolvedModule = moduleSpecifier && ((_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier)) == null ? void 0 : _a.resolvedModule); + const resolvedModule = moduleSpecifier && ((_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule); if (resolvedModule == null ? void 0 : resolvedModule.resolvedUsingTsExtension) { const changedExtension = changeAnyExtension(moduleSpecifier.text, getOutputExtension(moduleSpecifier.text, compilerOptions)); changes.replaceNode(sourceFile, moduleSpecifier, factory.createStringLiteral(changedExtension)); @@ -156125,38 +155632,8 @@ function createConstEqualsRequireDeclaration(name, quotedModuleSpecifier) { ], 2 /* Const */) ); } -function symbolHasMeaning({ declarations }, meaning) { - return some(declarations, (decl) => !!(getMeaningFromDeclaration(decl) & meaning)); -} -function moduleSymbolToValidIdentifier(moduleSymbol, target, forceCapitalize) { - return moduleSpecifierToValidIdentifier(removeFileExtension(stripQuotes(moduleSymbol.name)), target, forceCapitalize); -} -function moduleSpecifierToValidIdentifier(moduleSpecifier, target, forceCapitalize) { - const baseName = getBaseFileName(removeSuffix(moduleSpecifier, "/index")); - let res = ""; - let lastCharWasValid = true; - const firstCharCode = baseName.charCodeAt(0); - if (isIdentifierStart(firstCharCode, target)) { - res += String.fromCharCode(firstCharCode); - if (forceCapitalize) { - res = res.toUpperCase(); - } - } else { - lastCharWasValid = false; - } - for (let i = 1; i < baseName.length; i++) { - const ch = baseName.charCodeAt(i); - const isValid = isIdentifierPart(ch, target); - if (isValid) { - let char = String.fromCharCode(ch); - if (!lastCharWasValid) { - char = char.toUpperCase(); - } - res += char; - } - lastCharWasValid = isValid; - } - return !isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; +function symbolFlagsHaveMeaning(flags, meaning) { + return meaning === 7 /* All */ ? true : meaning & 1 /* Value */ ? !!(flags & 111551 /* Value */) : meaning & 2 /* Type */ ? !!(flags & 788968 /* Type */) : meaning & 4 /* Namespace */ ? !!(flags & 1920 /* Namespace */) : false; } function getImpliedNodeFormatForEmit(file, program) { return isFullSourceFile(file) ? program.getImpliedNodeFormatForEmit(file) : getImpliedNodeFormatForEmitWorker(file, program.getCompilerOptions()); @@ -156184,8 +155661,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span, program, preferences, host } = context; const info = getInfo6(program, sourceFile, span); - if (info === void 0) - return; + if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info)); return [createCodeFixAction(fixId17, changes, Diagnostics.Add_extends_constraint, fixId17, Diagnostics.Add_extends_constraint_to_all_type_parameters)]; }, @@ -156208,20 +155684,16 @@ registerCodeFix({ }); function getInfo6(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) - return; + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.This_type_parameter_might_need_an_extends_0_constraint.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) - return; + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; let declaration = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (declaration === void 0) - return; + if (declaration === void 0) return; if (isIdentifier(declaration) && isTypeParameterDeclaration(declaration.parent)) { declaration = declaration.parent; } if (isTypeParameterDeclaration(declaration)) { - if (isMappedTypeNode(declaration.parent)) - return; + if (isMappedTypeNode(declaration.parent)) return; const token = getTokenAtPosition(sourceFile, span.start); const checker = program.getTypeChecker(); const constraint = tryGetConstraintType(checker, token) || tryGetConstraintFromDiagnosticMessage(related.messageText); @@ -156346,12 +155818,11 @@ registerCodeFix({ getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { const { errorCode, span } = context; const info = errorCodeFixIdMap[errorCode]; - if (!info) - return emptyArray; - const { descriptions, fixId: fixId53, fixAllDescriptions } = info; + if (!info) return emptyArray; + const { descriptions, fixId: fixId55, fixAllDescriptions } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => dispatchChanges(changes2, context, errorCode, span.start)); return [ - createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId53, fixAllDescriptions) + createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId55, fixAllDescriptions) ]; }, fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], @@ -156423,8 +155894,7 @@ function isClassElementLikeHasJSDoc(node) { function findContainerClassElementLike(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const classElement = findAncestor(token, (node) => { - if (isClassLike(node)) - return "quit"; + if (isClassLike(node)) return "quit"; return isClassElementLikeHasJSDoc(node); }); Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); @@ -156480,8 +155950,7 @@ registerCodeFix({ }); function doChange15(changes, sourceFile, pos, checker) { const token = getTokenAtPosition(sourceFile, pos); - if (!isThis(token)) - return void 0; + if (!isThis(token)) return void 0; const fn = getThisContainer( token, /*includeArrowFunctions*/ @@ -156489,8 +155958,7 @@ function doChange15(changes, sourceFile, pos, checker) { /*includeClassComputedPropertyName*/ false ); - if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) - return void 0; + if (!isFunctionDeclaration(fn) && !isFunctionExpression(fn)) return void 0; if (!isSourceFile(getThisContainer( fn, /*includeArrowFunctions*/ @@ -156531,8 +155999,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span, program } = context; const info = getInfo7(sourceFile, span.start, program); - if (info === void 0) - return void 0; + if (info === void 0) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info)); return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)]; }, @@ -156542,8 +156009,7 @@ registerCodeFix({ const exports2 = /* @__PURE__ */ new Map(); eachDiagnostic(context, errorCodes23, (diag2) => { const info = getInfo7(diag2.file, diag2.start, program); - if (info === void 0) - return void 0; + if (info === void 0) return void 0; const { exportName, node, moduleSourceFile } = info; if (tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly) === void 0 && canHaveExportModifier(node)) { changes.insertExportModifier(moduleSourceFile, node); @@ -156582,27 +156048,20 @@ function getInfo7(sourceFile, pos, program) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { const importDeclaration = findAncestor(token, isImportDeclaration); - if (importDeclaration === void 0) - return void 0; + if (importDeclaration === void 0) return void 0; const moduleSpecifier = isStringLiteral(importDeclaration.moduleSpecifier) ? importDeclaration.moduleSpecifier : void 0; - if (moduleSpecifier === void 0) - return void 0; - const resolvedModule = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier)) == null ? void 0 : _a.resolvedModule; - if (resolvedModule === void 0) - return void 0; + if (moduleSpecifier === void 0) return void 0; + const resolvedModule = (_a = program.getResolvedModuleFromModuleSpecifier(moduleSpecifier, sourceFile)) == null ? void 0 : _a.resolvedModule; + if (resolvedModule === void 0) return void 0; const moduleSourceFile = program.getSourceFile(resolvedModule.resolvedFileName); - if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) - return void 0; + if (moduleSourceFile === void 0 || isSourceFileFromLibrary(program, moduleSourceFile)) return void 0; const moduleSymbol = moduleSourceFile.symbol; const locals = (_b = tryCast(moduleSymbol.valueDeclaration, canHaveLocals)) == null ? void 0 : _b.locals; - if (locals === void 0) - return void 0; + if (locals === void 0) return void 0; const localSymbol = locals.get(token.escapedText); - if (localSymbol === void 0) - return void 0; + if (localSymbol === void 0) return void 0; const node = getNodeOfSymbol(localSymbol); - if (node === void 0) - return void 0; + if (node === void 0) return void 0; const exportName = { node: token, isTypeOnly: isTypeDeclaration(node) }; return { exportName, node, moduleSourceFile, moduleSpecifier: moduleSpecifier.text }; } @@ -156758,8 +156217,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, errorCode } = context; const info = getInfo8(sourceFile, context.span.start, context, errorCode); - if (!info) - return void 0; + if (!info) return void 0; const { node, suggestedSymbol } = info; const target = getEmitScriptTarget(context.host.getCompilationSettings()); const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target)); @@ -156769,15 +156227,13 @@ registerCodeFix({ getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { const info = getInfo8(diag2.file, diag2.start, context, diag2.code); const target = getEmitScriptTarget(context.host.getCompilationSettings()); - if (info) - doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); + if (info) doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }) }); function getInfo8(sourceFile, pos, context, errorCode) { const node = getTokenAtPosition(sourceFile, pos); const parent2 = node.parent; - if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) - return void 0; + if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) return void 0; const checker = context.program.getTypeChecker(); let suggestedSymbol; if (isPropertyAccessExpression(parent2) && parent2.name === node) { @@ -156798,7 +156254,7 @@ function getInfo8(sourceFile, pos, context, errorCode) { } else if (isImportSpecifier(parent2) && parent2.name === node) { Debug.assertNode(node, isIdentifier, "Expected an identifier for spelling (import)"); const importDeclaration = findAncestor(node, isImportDeclaration); - const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(context, importDeclaration); + const resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(context, importDeclaration, sourceFile); if (resolvedSourceFile && resolvedSourceFile.symbol) { suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); } @@ -156848,13 +156304,11 @@ function convertSemanticMeaningToSymbolFlags(meaning) { } return flags; } -function getResolvedSourceFileFromImportDeclaration(context, importDeclaration) { +function getResolvedSourceFileFromImportDeclaration(context, importDeclaration, importingFile) { var _a; - if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) - return void 0; - const resolvedModule = (_a = context.program.getResolvedModuleFromModuleSpecifier(importDeclaration.moduleSpecifier)) == null ? void 0 : _a.resolvedModule; - if (!resolvedModule) - return void 0; + if (!importDeclaration || !isStringLiteralLike(importDeclaration.moduleSpecifier)) return void 0; + const resolvedModule = (_a = context.program.getResolvedModuleFromModuleSpecifier(importDeclaration.moduleSpecifier, importingFile)) == null ? void 0 : _a.resolvedModule; + if (!resolvedModule) return void 0; return context.program.getSourceFile(resolvedModule.resolvedFileName); } @@ -156874,8 +156328,7 @@ registerCodeFix({ getCodeActions: function getCodeActionsToCorrectReturnValue(context) { const { program, sourceFile, span: { start }, errorCode } = context; const info = getInfo9(program.getTypeChecker(), sourceFile, start, errorCode); - if (!info) - return void 0; + if (!info) return void 0; if (info.kind === 0 /* MissingReturnStatement */) { return append( [getActionForfixAddReturnStatement(context, info.expression, info.statement)], @@ -156887,15 +156340,13 @@ registerCodeFix({ }, getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); - if (!info) - return void 0; + if (!info) return void 0; switch (context.fixId) { case fixIdAddReturnStatement: addReturnStatement(changes, diag2.file, info.expression, info.statement); break; case fixRemoveBracesFromArrowFunctionBody: - if (!isArrowFunction(info.declaration)) - return void 0; + if (!isArrowFunction(info.declaration)) return void 0; removeBlockBodyBrace( changes, diag2.file, @@ -156907,8 +156358,7 @@ registerCodeFix({ ); break; case fixIdWrapTheBlockWithParen: - if (!isArrowFunction(info.declaration)) - return void 0; + if (!isArrowFunction(info.declaration)) return void 0; wrapBlockWithParen(changes, diag2.file, info.declaration, info.expression); break; default: @@ -156930,8 +156380,7 @@ function createObjectTypeFromLabeledExpression(checker, label, expression) { ); } function getFixInfo(checker, declaration, expectType, isFunctionType) { - if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) - return void 0; + if (!declaration.body || !isBlock(declaration.body) || length(declaration.body.statements) !== 1) return void 0; const firstStatement = first(declaration.body.statements); if (isExpressionStatement(firstStatement) && checkFixedAssignableTo(checker, declaration, checker.getTypeAtLocation(firstStatement.expression), expectType, isFunctionType)) { return { @@ -157011,13 +156460,11 @@ function checkFixedAssignableTo(checker, declaration, exprType, type, isFunction } function getInfo9(checker, sourceFile, position, errorCode) { const node = getTokenAtPosition(sourceFile, position); - if (!node.parent) - return void 0; + if (!node.parent) return void 0; const declaration = findAncestor(node.parent, isFunctionLikeDeclaration); switch (errorCode) { case Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code: - if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) - return void 0; + if (!declaration || !declaration.body || !declaration.type || !rangeContainsRange(declaration.type, node)) return void 0; return getFixInfo( checker, declaration, @@ -157026,14 +156473,11 @@ function getInfo9(checker, sourceFile, position, errorCode) { false ); case Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code: - if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) - return void 0; + if (!declaration || !isCallExpression(declaration.parent) || !declaration.body) return void 0; const pos = declaration.parent.arguments.indexOf(declaration); - if (pos === -1) - return void 0; + if (pos === -1) return void 0; const type = checker.getContextualTypeForArgumentAtIndex(declaration.parent, pos); - if (!type) - return void 0; + if (!type) return void 0; return getFixInfo( checker, declaration, @@ -157042,11 +156486,9 @@ function getInfo9(checker, sourceFile, position, errorCode) { true ); case Diagnostics.Type_0_is_not_assignable_to_type_1.code: - if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) - return void 0; + if (!isDeclarationName(node) || !isVariableLike(node.parent) && !isJsxAttribute(node.parent)) return void 0; const initializer = getVariableLikeInitializer(node.parent); - if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) - return void 0; + if (!initializer || !isFunctionLikeDeclaration(initializer) || !initializer.body) return void 0; return getFixInfo( checker, initializer, @@ -157156,7 +156598,7 @@ registerCodeFix({ }, fixIds: [fixMissingMember, fixMissingFunctionDeclaration, fixMissingProperties, fixMissingAttributes], getAllCodeActions: (context) => { - const { program, fixId: fixId53 } = context; + const { program, fixId: fixId55 } = context; const checker = program.getTypeChecker(); const seen = /* @__PURE__ */ new Map(); const typeDeclToMembers = /* @__PURE__ */ new Map(); @@ -157166,11 +156608,11 @@ registerCodeFix({ if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + (info.kind === 3 /* ObjectLiteral */ ? info.identifier : info.token.text))) { return; } - if (fixId53 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) { + if (fixId55 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) { addFunctionDeclaration(changes, context, info); - } else if (fixId53 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) { + } else if (fixId55 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) { addObjectLiteralProperties(changes, context, info); - } else if (fixId53 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) { + } else if (fixId55 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) { addJsxAttributes(changes, context, info); } else { if (info.kind === 1 /* Enum */) { @@ -157191,8 +156633,7 @@ registerCodeFix({ if (supers == null ? void 0 : supers.some((superClassOrInterface) => { const superInfos = typeDeclToMembers.get(superClassOrInterface); return !!superInfos && superInfos.some(({ token: token2 }) => token2.text === info.token.text); - })) - continue; + })) continue; const { parentDeclaration, declSourceFile, modifierFlags, token, call, isJSFile } = info; if (call && !isPrivateIdentifier(token)) { addMethodDeclaration(context, changes, call, token, modifierFlags & 256 /* Static */, parentDeclaration, declSourceFile); @@ -157214,17 +156655,13 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) { - if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) - return void 0; + if (!(token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2) && isCallExpression(parent2.parent))) return void 0; const argIndex = findIndex(parent2.parent.arguments, (arg) => arg === parent2); - if (argIndex < 0) - return void 0; + if (argIndex < 0) return void 0; const signature = checker.getResolvedSignature(parent2.parent); - if (!(signature && signature.declaration && signature.parameters[argIndex])) - return void 0; + if (!(signature && signature.declaration && signature.parameters[argIndex])) return void 0; const param = signature.parameters[argIndex].valueDeclaration; - if (!(param && isParameter(param) && isIdentifier(param.name))) - return void 0; + if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0; const properties = arrayFrom(checker.getUnmatchedProperties( checker.getTypeAtLocation(parent2), checker.getParameterType(signature, argIndex), @@ -157233,8 +156670,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { /*matchDiscriminantProperties*/ false )); - if (!length(properties)) - return void 0; + if (!length(properties)) return void 0; return { kind: 3 /* ObjectLiteral */, token: param.name, identifier: param.name.text, properties, parentDeclaration: parent2 }; } if (token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2)) { @@ -157247,13 +156683,11 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { /*matchDiscriminantProperties*/ false )); - if (!length(properties)) - return void 0; + if (!length(properties)) return void 0; const identifier = ""; return { kind: 3 /* ObjectLiteral */, token: parent2, identifier, properties, parentDeclaration: parent2 }; } - if (!isMemberName(token)) - return void 0; + if (!isMemberName(token)) return void 0; if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) { const targetType = checker.getContextualType(token) || checker.getTypeAtLocation(token); const properties = arrayFrom(checker.getUnmatchedProperties( @@ -157264,35 +156698,30 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { /*matchDiscriminantProperties*/ false )); - if (!length(properties)) - return void 0; + if (!length(properties)) return void 0; return { kind: 3 /* ObjectLiteral */, token, identifier: token.text, properties, parentDeclaration: parent2.initializer }; } if (isIdentifier(token) && isJsxOpeningLikeElement(token.parent)) { const target = getEmitScriptTarget(program.getCompilerOptions()); const attributes = getUnmatchedAttributes(checker, target, token.parent); - if (!length(attributes)) - return void 0; + if (!length(attributes)) return void 0; return { kind: 4 /* JsxAttributes */, token, attributes, parentDeclaration: token.parent }; } if (isIdentifier(token)) { const type = (_a = checker.getContextualType(token)) == null ? void 0 : _a.getNonNullableType(); if (type && getObjectFlags(type) & 16 /* Anonymous */) { const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */)); - if (signature === void 0) - return void 0; + if (signature === void 0) return void 0; return { kind: 5 /* Signature */, token, signature, sourceFile, parentDeclaration: findScope(token) }; } if (isCallExpression(parent2) && parent2.expression === token) { return { kind: 2 /* Function */, token, call: parent2, sourceFile, modifierFlags: 0 /* None */, parentDeclaration: findScope(token) }; } } - if (!isPropertyAccessExpression(parent2)) - return void 0; + if (!isPropertyAccessExpression(parent2)) return void 0; const leftExpressionType = skipConstraint(checker.getTypeAtLocation(parent2.expression)); const symbol = leftExpressionType.symbol; - if (!symbol || !symbol.declarations) - return void 0; + if (!symbol || !symbol.declarations) return void 0; if (isIdentifier(token) && isCallExpression(parent2.parent)) { const moduleDeclaration = find(symbol.declarations, isModuleDeclaration); const moduleDeclarationSourceFile = moduleDeclaration == null ? void 0 : moduleDeclaration.getSourceFile(); @@ -157300,20 +156729,17 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleDeclaration }; } const moduleSourceFile = find(symbol.declarations, isSourceFile); - if (sourceFile.commonJsModuleIndicator) - return void 0; + if (sourceFile.commonJsModuleIndicator) return void 0; if (moduleSourceFile && !isSourceFileFromLibrary(program, moduleSourceFile)) { return { kind: 2 /* Function */, token, call: parent2.parent, sourceFile: moduleSourceFile, modifierFlags: 32 /* Export */, parentDeclaration: moduleSourceFile }; } } const classDeclaration = find(symbol.declarations, isClassLike); - if (!classDeclaration && isPrivateIdentifier(token)) - return void 0; + if (!classDeclaration && isPrivateIdentifier(token)) return void 0; const declaration = classDeclaration || find(symbol.declarations, (d) => isInterfaceDeclaration(d) || isTypeLiteralNode(d)); if (declaration && !isSourceFileFromLibrary(program, declaration.getSourceFile())) { const makeStatic = !isTypeLiteralNode(declaration) && (leftExpressionType.target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); - if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) - return void 0; + if (makeStatic && (isPrivateIdentifier(token) || isInterfaceDeclaration(declaration))) return void 0; const declSourceFile = declaration.getSourceFile(); const modifierFlags = isTypeLiteralNode(declaration) ? 0 /* None */ : (makeStatic ? 256 /* Static */ : 0 /* None */) | (startsWithUnderscore(token.text) ? 2 /* Private */ : 0 /* None */); const isJSFile = isSourceFileJS(declSourceFile); @@ -157440,8 +156866,7 @@ function addPropertyDeclaration(changeTracker, sourceFile, node, tokenName, type function getNodeToInsertPropertyAfter(node) { let res; for (const member of node.members) { - if (!isPropertyDeclaration(member)) - break; + if (!isPropertyDeclaration(member)) break; res = member; } return res; @@ -157655,11 +157080,9 @@ function tryGetValueFromType(context, checker, importAdder, quotePreference, typ } if (getObjectFlags(type) & 16 /* Anonymous */) { const decl = find(type.symbol.declarations || emptyArray, or(isFunctionTypeNode, isMethodSignature, isMethodDeclaration)); - if (decl === void 0) - return createUndefined(); + if (decl === void 0) return createUndefined(); const signature = checker.getSignaturesOfType(type, 0 /* Call */); - if (signature === void 0) - return createUndefined(); + if (signature === void 0) return createUndefined(); const func = createSignatureDeclarationFromSignature( 218 /* FunctionExpression */, context, @@ -157680,11 +157103,9 @@ function tryGetValueFromType(context, checker, importAdder, quotePreference, typ } if (getObjectFlags(type) & 1 /* Class */) { const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration)) - return createUndefined(); + if (classDeclaration === void 0 || hasAbstractModifier(classDeclaration)) return createUndefined(); const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); - if (constructorDeclaration && length(constructorDeclaration.parameters)) - return createUndefined(); + if (constructorDeclaration && length(constructorDeclaration.parameters)) return createUndefined(); return factory.createNewExpression( factory.createIdentifier(type.symbol.name), /*typeArguments*/ @@ -157703,11 +157124,9 @@ function isObjectLiteralType(type) { } function getUnmatchedAttributes(checker, target, source) { const attrsType = checker.getContextualType(source.attributes); - if (attrsType === void 0) - return emptyArray; + if (attrsType === void 0) return emptyArray; const targetProps = attrsType.getProperties(); - if (!length(targetProps)) - return emptyArray; + if (!length(targetProps)) return emptyArray; const seenNames = /* @__PURE__ */ new Set(); for (const sourceProp of source.attributes.properties) { if (isJsxAttribute(sourceProp)) { @@ -157738,8 +157157,7 @@ function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) void 0, 1073741824 /* WriteComputedProps */ ); - if (prop && isComputedPropertyName(prop)) - return prop; + if (prop && isComputedPropertyName(prop)) return prop; } return createPropertyNameNodeForIdentifierOrLiteral( symbol.name, @@ -157754,8 +157172,7 @@ function createPropertyNameFromSymbol(symbol, target, quotePreference, checker) function findScope(node) { if (findAncestor(node, isJsxExpression)) { const returnStatement = findAncestor(node.parent, isReturnStatement); - if (returnStatement) - return returnStatement; + if (returnStatement) return returnStatement; } return getSourceFileOfNode(node); } @@ -157796,8 +157213,7 @@ registerCodeFix({ fixIds: [addMissingParamFixId, addOptionalParamFixId], getCodeActions(context) { const info = getInfo11(context.sourceFile, context.program, context.span.start); - if (info === void 0) - return void 0; + if (info === void 0) return void 0; const { name, declarations, newParameters, newOptionalParameters } = info; const actions2 = []; if (length(newParameters)) { @@ -157805,7 +157221,7 @@ registerCodeFix({ actions2, createCodeFixAction( addMissingParamFixId, - ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.sourceFile, declarations, newParameters)), + ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.program, context.preferences, context.host, declarations, newParameters)), [length(newParameters) > 1 ? Diagnostics.Add_missing_parameters_to_0 : Diagnostics.Add_missing_parameter_to_0, name], addMissingParamFixId, Diagnostics.Add_all_missing_parameters @@ -157817,7 +157233,7 @@ registerCodeFix({ actions2, createCodeFixAction( addOptionalParamFixId, - ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.sourceFile, declarations, newOptionalParameters)), + ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.program, context.preferences, context.host, declarations, newOptionalParameters)), [length(newOptionalParameters) > 1 ? Diagnostics.Add_optional_parameters_to_0 : Diagnostics.Add_optional_parameter_to_0, name], addOptionalParamFixId, Diagnostics.Add_all_optional_parameters @@ -157831,10 +157247,10 @@ registerCodeFix({ if (info) { const { declarations, newParameters, newOptionalParameters } = info; if (context.fixId === addMissingParamFixId) { - doChange19(changes, context.sourceFile, declarations, newParameters); + doChange19(changes, context.program, context.preferences, context.host, declarations, newParameters); } if (context.fixId === addOptionalParamFixId) { - doChange19(changes, context.sourceFile, declarations, newOptionalParameters); + doChange19(changes, context.program, context.preferences, context.host, declarations, newOptionalParameters); } } }) @@ -157914,14 +157330,17 @@ function tryGetName2(node) { function typeToTypeNode(checker, type, enclosingDeclaration) { return checker.typeToTypeNode(checker.getWidenedType(type), enclosingDeclaration, 1 /* NoTruncation */) ?? factory.createKeywordTypeNode(159 /* UnknownKeyword */); } -function doChange19(changes, sourceFile, declarations, newParameters) { +function doChange19(changes, program, preferences, host, declarations, newParameters) { + const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); forEach(declarations, (declaration) => { + const sourceFile = getSourceFileOfNode(declaration); + const importAdder = createImportAdder(sourceFile, program, preferences, host); if (length(declaration.parameters)) { changes.replaceNodeRangeWithNodes( sourceFile, first(declaration.parameters), last(declaration.parameters), - updateParameters(declaration, newParameters), + updateParameters(importAdder, scriptTarget, declaration, newParameters), { joiner: ", ", indentation: 0, @@ -157930,7 +157349,7 @@ function doChange19(changes, sourceFile, declarations, newParameters) { } ); } else { - forEach(updateParameters(declaration, newParameters), (parameter, index) => { + forEach(updateParameters(importAdder, scriptTarget, declaration, newParameters), (parameter, index) => { if (length(declaration.parameters) === 0 && index === 0) { changes.insertNodeAt(sourceFile, declaration.parameters.end, parameter); } else { @@ -157938,6 +157357,7 @@ function doChange19(changes, sourceFile, declarations, newParameters) { } }); } + importAdder.writeFixes(changes); }); } function isConvertibleSignatureDeclaration(node) { @@ -157951,7 +157371,7 @@ function isConvertibleSignatureDeclaration(node) { return false; } } -function updateParameters(node, newParameters) { +function updateParameters(importAdder, scriptTarget, node, newParameters) { const parameters = map(node.parameters, (p) => factory.createParameterDeclaration( p.modifiers, p.dotDotDotToken, @@ -157971,7 +157391,7 @@ function updateParameters(node, newParameters) { declaration.dotDotDotToken, declaration.name, prev && prev.questionToken ? factory.createToken(58 /* QuestionToken */) : declaration.questionToken, - declaration.type, + getParameterType(importAdder, declaration.type, scriptTarget), declaration.initializer ) ); @@ -158012,6 +157432,14 @@ function createParameter(name, type, questionToken) { function isOptionalPos(declarations, pos) { return length(declarations) && some(declarations, (d) => pos < length(d.parameters) && !!d.parameters[pos] && d.parameters[pos].questionToken === void 0); } +function getParameterType(importAdder, typeNode, scriptTarget) { + const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); + if (importableReference) { + importSymbols(importAdder, importableReference.symbols); + return importableReference.typeNode; + } + return typeNode; +} // src/services/codefixes/fixCannotFindModule.ts var fixName2 = "fixCannotFindModule"; @@ -158026,8 +157454,7 @@ registerCodeFix({ getCodeActions: function getCodeActionsToFixNotFoundModule(context) { const { host, sourceFile, span: { start } } = context; const packageName = tryGetImportedPackageName(sourceFile, start); - if (packageName === void 0) - return void 0; + if (packageName === void 0) return void 0; const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); return typesPackageName === void 0 ? [] : [createCodeFixAction( fixName2, @@ -158043,8 +157470,7 @@ registerCodeFix({ getAllCodeActions: (context) => { return codeFixAll(context, errorCodes30, (_changes, diag2, commands) => { const packageName = tryGetImportedPackageName(diag2.file, diag2.start); - if (packageName === void 0) - return void 0; + if (packageName === void 0) return void 0; switch (context.fixId) { case fixIdInstallTypesPackage: { const pkg = getTypesPackageNameToInstall(packageName, context.host, diag2.code); @@ -158064,8 +157490,7 @@ function getInstallCommand(fileName, packageName) { } function tryGetImportedPackageName(sourceFile, pos) { const moduleSpecifierText = tryCast(getTokenAtPosition(sourceFile, pos), isStringLiteral); - if (!moduleSpecifierText) - return void 0; + if (!moduleSpecifierText) return void 0; const moduleName = moduleSpecifierText.text; const { packageName } = parsePackageName(moduleName); return isExternalModuleNameRelative(packageName) ? void 0 : packageName; @@ -158129,8 +157554,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span } = context; const nodes = getNodes(sourceFile, span.start); - if (!nodes) - return void 0; + if (!nodes) return void 0; const { constructor, superCall } = nodes; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, constructor, superCall)); return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; @@ -158141,8 +157565,7 @@ registerCodeFix({ const seenClasses = /* @__PURE__ */ new Map(); return codeFixAll(context, errorCodes32, (changes, diag2) => { const nodes = getNodes(diag2.file, diag2.start); - if (!nodes) - return; + if (!nodes) return; const { constructor, superCall } = nodes; if (addToSeen(seenClasses, getNodeId(constructor.parent))) { doChange20(changes, sourceFile, constructor, superCall); @@ -158156,8 +157579,7 @@ function doChange20(changes, sourceFile, constructor, superCall) { } function getNodes(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); - if (token.kind !== 110 /* ThisKeyword */) - return void 0; + if (token.kind !== 110 /* ThisKeyword */) return void 0; const constructor = getContainingFunction(token); const superCall = findSuperCall(constructor.body); return superCall && !superCall.expression.arguments.some((arg) => isPropertyAccessExpression(arg) && arg.expression === token) ? { constructor, superCall } : void 0; @@ -158234,8 +157656,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span, program } = context; const info = getInfo12(program, sourceFile, span); - if (info === void 0) - return; + if (info === void 0) return; const { suggestion, expression, arg } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, arg, expression)); return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; @@ -158252,14 +157673,11 @@ registerCodeFix({ }); function getInfo12(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); - if (diag2 === void 0 || diag2.relatedInformation === void 0) - return; + if (diag2 === void 0 || diag2.relatedInformation === void 0) return; const related = find(diag2.relatedInformation, (related2) => related2.code === Diagnostics.Did_you_mean_0.code); - if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) - return; + if (related === void 0 || related.file === void 0 || related.start === void 0 || related.length === void 0) return; const token = findAncestorMatchingSpan(related.file, createTextSpan(related.start, related.length)); - if (token === void 0) - return; + if (token === void 0) return; if (isExpression(token) && isBinaryExpression(token.parent)) { return { suggestion: getSuggestion(related.messageText), expression: token.parent, arg: token }; } @@ -158311,8 +157729,7 @@ registerCodeFix({ if (targetOutOfRange) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (tracker) => { const configObject = getTsConfigObjectLiteralExpression(configFile); - if (!configObject) - return; + if (!configObject) return; const options = [["target", factory.createStringLiteral("es2017")]]; if (moduleKind === 1 /* CommonJS */) { options.push(["module", factory.createStringLiteral("commonjs")]); @@ -158356,8 +157773,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile } = context; const nodes = getNodes2(sourceFile, context.span.start); - if (!nodes) - return void 0; + if (!nodes) return void 0; const { extendsToken, heritageClauses } = nodes; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChanges2(t, sourceFile, extendsToken, heritageClauses)); return [createCodeFixAction(fixId30, changes, Diagnostics.Change_extends_to_implements, fixId30, Diagnostics.Change_all_extended_interfaces_to_implements)]; @@ -158365,8 +157781,7 @@ registerCodeFix({ fixIds: [fixId30], getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { const nodes = getNodes2(diag2.file, diag2.start); - if (nodes) - doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); + if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); }) }); function getNodes2(sourceFile, pos) { @@ -158412,8 +157827,7 @@ registerCodeFix({ fixIds: [fixId31], getAllCodeActions: (context) => codeFixAll(context, errorCodes38, (changes, diag2) => { const info = getInfo13(diag2.file, diag2.start, diag2.code); - if (info) - doChange25(changes, context.sourceFile, info); + if (info) doChange25(changes, context.sourceFile, info); }) }); function getInfo13(sourceFile, pos, diagCode) { @@ -158529,8 +157943,7 @@ function getDeleteAction(context, { name, jsDocHost, jsDocParameterTag }) { ); } function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTag }) { - if (!length(signature.parameters)) - return void 0; + if (!length(signature.parameters)) return void 0; const sourceFile = context.sourceFile; const tags = getJSDocTags(signature); const names = /* @__PURE__ */ new Set(); @@ -158540,8 +157953,7 @@ function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTa } } const parameterName = firstDefined(signature.parameters, (p) => isIdentifier(p.name) && !names.has(p.name.escapedText) ? p.name.getText(sourceFile) : void 0); - if (parameterName === void 0) - return void 0; + if (parameterName === void 0) return void 0; const newJSDocParameterTag = factory.updateJSDocParameterTag( jsDocParameterTag, jsDocParameterTag.tagName, @@ -158574,8 +157986,7 @@ registerCodeFix({ errorCodes: errorCodes41, getCodeActions: (context) => { const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); - if (!importDeclaration) - return; + if (!importDeclaration) return; const namespaceChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => importDeclaration.kind === 276 /* ImportSpecifier */ && doNamespaceImportChange(t, context.sourceFile, importDeclaration, context.program)); const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); let actions2; @@ -158591,8 +158002,7 @@ registerCodeFix({ }); function getImportDeclaration(sourceFile, program, start) { const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); - if (!identifier || identifier.parent.kind !== 183 /* TypeReference */) - return; + if (!identifier || identifier.parent.kind !== 183 /* TypeReference */) return; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(identifier); return find((symbol == null ? void 0 : symbol.declarations) || emptyArray, or(isImportClause, isImportSpecifier, isImportEqualsDeclaration)); @@ -158608,8 +158018,7 @@ function doTypeOnlyImportChange(changes, sourceFile, importDeclaration, program) } const checker = program.getTypeChecker(); const importsValue = !!forEachImportClauseDeclaration(importClause, (decl) => { - if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */) - return true; + if (skipAlias(decl.symbol, checker).flags & 111551 /* Value */) return true; }); if (importsValue) { return; @@ -158836,8 +158245,7 @@ function deleteDestructuring(context, changes, sourceFile, { parent: parent2 }) } } function tryPrefixDeclaration(changes, errorCode, sourceFile, token) { - if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) - return; + if (errorCode === Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code) return; if (token.kind === 140 /* InferKeyword */) { token = cast(token.parent, isInferTypeNode).typeParameter.name; } @@ -158872,8 +158280,7 @@ function tryDeleteDeclaration(sourceFile, token, changes, checker, sourceFiles, tryDeleteDeclarationWorker(token, changes, sourceFile, checker, sourceFiles, program, cancellationToken, isFixAll); if (isIdentifier(token)) { ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(token, checker, sourceFile, (ref) => { - if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) - ref = ref.parent; + if (isPropertyAccessExpression(ref.parent) && ref.parent.name === ref) ref = ref.parent; if (!isFixAll && mayDeleteExpression(ref)) { changes.delete(sourceFile, ref.parent.parent); } @@ -158922,8 +158329,7 @@ function mayDeleteParameter(checker, sourceFile, parameter, sourceFiles, program const isSuperCall2 = isSuperKeyword(reference.node) && isCallExpression(reference.node.parent) && reference.node.parent.arguments.length > index; const isSuperMethodCall = isPropertyAccessExpression(reference.node.parent) && isSuperKeyword(reference.node.parent.expression) && isCallExpression(reference.node.parent.parent) && reference.node.parent.parent.arguments.length > index; const isOverriddenMethod = (isMethodDeclaration(reference.node.parent) || isMethodSignature(reference.node.parent)) && reference.node.parent !== parameter.parent && reference.node.parent.parameters.length > index; - if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod) - return false; + if (isSuperCall2 || isSuperMethodCall || isOverriddenMethod) return false; } } } @@ -158974,8 +158380,7 @@ registerCodeFix({ errorCodes: errorCodes43, getCodeActions(context) { const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); - if (syntacticDiagnostics.length) - return; + if (syntacticDiagnostics.length) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)]; }, @@ -159024,8 +158429,7 @@ function doChange27(changes, sourceFile, start, length2, errorCode) { function lastWhere(a, pred) { let last2; for (const value of a) { - if (!pred(value)) - break; + if (!pred(value)) break; last2 = value; } return last2; @@ -159071,8 +158475,7 @@ registerCodeFix({ const { sourceFile } = context; const checker = context.program.getTypeChecker(); const info = getInfo15(sourceFile, context.span.start, checker); - if (!info) - return void 0; + if (!info) return void 0; const { typeNode, type } = info; const original = typeNode.getText(sourceFile); const actions2 = [fix(type, fixIdPlain, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript)]; @@ -159080,21 +158483,20 @@ registerCodeFix({ actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions2; - function fix(type2, fixId53, fixAllDescription) { + function fix(type2, fixId55, fixAllDescription) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, typeNode, type2, checker)); - return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId53, fixAllDescription); + return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId55, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions(context) { - const { fixId: fixId53, program, sourceFile } = context; + const { fixId: fixId55, program, sourceFile } = context; const checker = program.getTypeChecker(); return codeFixAll(context, errorCodes45, (changes, err) => { const info = getInfo15(err.file, err.start, checker); - if (!info) - return; + if (!info) return; const { typeNode, type } = info; - const fixedType = typeNode.kind === 314 /* JSDocNullableType */ && fixId53 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + const fixedType = typeNode.kind === 314 /* JSDocNullableType */ && fixId55 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange29(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -159160,15 +158562,13 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span } = context; const callName = getCallName(sourceFile, span.start); - if (!callName) - return; + if (!callName) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, context.sourceFile, callName)); return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes46, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); - if (callName) - doChange30(changes, diag2.file, callName); + if (callName) doChange30(changes, diag2.file, callName); }) }); function doChange30(changes, sourceFile, name) { @@ -159189,31 +158589,890 @@ function getCallName(sourceFile, start) { return void 0; } -// src/services/codefixes/fixAwaitInSyncFunction.ts -var fixId36 = "fixAwaitInSyncFunction"; +// src/services/codefixes/fixMissingTypeAnnotationOnExports.ts +var fixId36 = "fixMissingTypeAnnotationOnExports"; +var addAnnotationFix = "add-annotation"; +var addInlineTypeAssertion = "add-type-assertion"; +var extractExpression = "extract-expression"; var errorCodes47 = [ + Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, + Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, + Diagnostics.At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, + Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, + Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, + Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, + Diagnostics.Expression_type_can_t_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Binding_elements_can_t_be_exported_directly_with_isolatedDeclarations.code, + Diagnostics.Computed_property_names_on_class_or_object_literals_cannot_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Computed_properties_must_be_number_or_string_literals_variables_or_dotted_expressions_with_isolatedDeclarations.code, + Diagnostics.Enum_member_initializers_must_be_computable_without_references_to_external_symbols_with_isolatedDeclarations.code, + Diagnostics.Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations.code, + Diagnostics.Objects_that_contain_shorthand_properties_can_t_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Objects_that_contain_spread_assignments_can_t_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Arrays_with_spread_elements_can_t_inferred_with_isolatedDeclarations.code, + Diagnostics.Default_exports_can_t_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations.code, + Diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function.code, + Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_it_s_type_This_is_not_supported_with_isolatedDeclarations.code, + Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations.code, + Diagnostics.Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit.code +]; +var canHaveTypeAnnotation = /* @__PURE__ */ new Set([ + 177 /* GetAccessor */, + 174 /* MethodDeclaration */, + 172 /* PropertyDeclaration */, + 262 /* FunctionDeclaration */, + 218 /* FunctionExpression */, + 219 /* ArrowFunction */, + 260 /* VariableDeclaration */, + 169 /* Parameter */, + 277 /* ExportAssignment */, + 263 /* ClassDeclaration */, + 206 /* ObjectBindingPattern */, + 207 /* ArrayBindingPattern */ +]); +var declarationEmitNodeBuilderFlags2 = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */ | 1073741824 /* WriteComputedProps */; +registerCodeFix({ + errorCodes: errorCodes47, + fixIds: [fixId36], + getCodeActions(context) { + const fixes = []; + addCodeAction(addAnnotationFix, fixes, context, 0 /* Full */, (f) => f.addTypeAnnotation(context.span)); + addCodeAction(addAnnotationFix, fixes, context, 1 /* Relative */, (f) => f.addTypeAnnotation(context.span)); + addCodeAction(addAnnotationFix, fixes, context, 2 /* Widened */, (f) => f.addTypeAnnotation(context.span)); + addCodeAction(addInlineTypeAssertion, fixes, context, 0 /* Full */, (f) => f.addInlineAssertion(context.span)); + addCodeAction(addInlineTypeAssertion, fixes, context, 1 /* Relative */, (f) => f.addInlineAssertion(context.span)); + addCodeAction(addInlineTypeAssertion, fixes, context, 2 /* Widened */, (f) => f.addInlineAssertion(context.span)); + addCodeAction(extractExpression, fixes, context, 0 /* Full */, (f) => f.extractAsVariable(context.span)); + return fixes; + }, + getAllCodeActions: (context) => { + const changes = withContext(context, 0 /* Full */, (f) => { + eachDiagnostic(context, errorCodes47, (diag2) => { + f.addTypeAnnotation(diag2); + }); + }); + return createCombinedCodeActions(changes.textChanges); + } +}); +function addCodeAction(fixName8, fixes, context, typePrintMode, cb) { + const changes = withContext(context, typePrintMode, cb); + if (changes.result && changes.textChanges.length) { + fixes.push(createCodeFixAction( + fixName8, + changes.textChanges, + changes.result, + fixId36, + Diagnostics.Add_all_missing_type_annotations + )); + } +} +function withContext(context, typePrintMode, cb) { + const emptyInferenceResult = { typeNode: void 0, mutatedTarget: false }; + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const sourceFile = context.sourceFile; + const program = context.program; + const typeChecker = program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(program.getCompilerOptions()); + const importAdder = createImportAdder(context.sourceFile, context.program, context.preferences, context.host); + const fixedNodes = /* @__PURE__ */ new Set(); + const expandoPropertiesAdded = /* @__PURE__ */ new Set(); + const typePrinter = createPrinter({ + preserveSourceNewlines: false + }); + const result = cb({ addTypeAnnotation, addInlineAssertion, extractAsVariable }); + importAdder.writeFixes(changeTracker); + return { + result, + textChanges: changeTracker.getChanges() + }; + function addTypeAnnotation(span) { + const nodeWithDiag = getTokenAtPosition(sourceFile, span.start); + const expandoFunction = findExpandoFunction(nodeWithDiag); + if (expandoFunction) { + if (isFunctionDeclaration(expandoFunction)) { + return createNamespaceForExpandoProperties(expandoFunction); + } + return fixIsolatedDeclarationError(expandoFunction); + } + const nodeMissingType = findAncestorWithMissingType(nodeWithDiag); + if (nodeMissingType) { + return fixIsolatedDeclarationError(nodeMissingType); + } + return void 0; + } + function createNamespaceForExpandoProperties(expandoFunc) { + var _a; + if (expandoPropertiesAdded == null ? void 0 : expandoPropertiesAdded.has(expandoFunc)) return void 0; + expandoPropertiesAdded == null ? void 0 : expandoPropertiesAdded.add(expandoFunc); + const type = typeChecker.getTypeAtLocation(expandoFunc); + const elements = typeChecker.getPropertiesOfType(type); + if (!expandoFunc.name || elements.length === 0) return void 0; + const newProperties = []; + for (const symbol of elements) { + if (!isIdentifierText(symbol.name, getEmitScriptTarget(program.getCompilerOptions()))) continue; + if (symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration)) continue; + newProperties.push(factory.createVariableStatement( + [factory.createModifier(95 /* ExportKeyword */)], + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + symbol.name, + /*exclamationToken*/ + void 0, + typeToTypeNode2(typeChecker.getTypeOfSymbol(symbol), expandoFunc), + /*initializer*/ + void 0 + )] + ) + )); + } + if (newProperties.length === 0) return void 0; + const modifiers = []; + if ((_a = expandoFunc.modifiers) == null ? void 0 : _a.some((modifier) => modifier.kind === 95 /* ExportKeyword */)) { + modifiers.push(factory.createModifier(95 /* ExportKeyword */)); + } + modifiers.push(factory.createModifier(138 /* DeclareKeyword */)); + const namespace = factory.createModuleDeclaration( + modifiers, + expandoFunc.name, + factory.createModuleBlock(newProperties), + /*flags*/ + 32 /* Namespace */ | 128 /* ExportContext */ | 33554432 /* Ambient */ | 101441536 /* ContextFlags */ + ); + changeTracker.insertNodeAfter(sourceFile, expandoFunc, namespace); + return [Diagnostics.Annotate_types_of_properties_expando_function_in_a_namespace]; + } + function needsParenthesizedExpressionForAssertion(node) { + return !isEntityNameExpression(node) && !isCallExpression(node) && !isObjectLiteralExpression(node) && !isArrayLiteralExpression(node); + } + function createAsExpression(node, type) { + if (needsParenthesizedExpressionForAssertion(node)) { + node = factory.createParenthesizedExpression(node); + } + return factory.createAsExpression(node, type); + } + function createSatisfiesAsExpression(node, type) { + if (needsParenthesizedExpressionForAssertion(node)) { + node = factory.createParenthesizedExpression(node); + } + return factory.createAsExpression(factory.createSatisfiesExpression(node, getSynthesizedDeepClone(type)), type); + } + function addInlineAssertion(span) { + const nodeWithDiag = getTokenAtPosition(sourceFile, span.start); + const expandoFunction = findExpandoFunction(nodeWithDiag); + if (expandoFunction) return; + const targetNode = findBestFittingNode(nodeWithDiag, span); + if (!targetNode || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.parent)) return; + const isExpressionTarget = isExpression(targetNode); + const isShorthandPropertyAssignmentTarget = isShorthandPropertyAssignment(targetNode); + if (!isShorthandPropertyAssignmentTarget && isDeclaration(targetNode)) { + return void 0; + } + if (findAncestor(targetNode, isBindingPattern)) { + return void 0; + } + if (findAncestor(targetNode, isEnumMember)) { + return void 0; + } + if (isExpressionTarget && (findAncestor(targetNode, isHeritageClause) || findAncestor(targetNode, isTypeNode))) { + return void 0; + } + if (isSpreadElement(targetNode)) { + return void 0; + } + const variableDeclaration = findAncestor(targetNode, isVariableDeclaration); + const type = variableDeclaration && typeChecker.getTypeAtLocation(variableDeclaration); + if (type && type.flags & 8192 /* UniqueESSymbol */) { + return void 0; + } + if (!(isExpressionTarget || isShorthandPropertyAssignmentTarget)) return void 0; + const { typeNode, mutatedTarget } = inferType(targetNode, type); + if (!typeNode || mutatedTarget) return void 0; + if (isShorthandPropertyAssignmentTarget) { + changeTracker.insertNodeAt( + sourceFile, + targetNode.end, + createAsExpression( + getSynthesizedDeepClone(targetNode.name), + typeNode + ), + { + prefix: ": " + } + ); + } else if (isExpressionTarget) { + changeTracker.replaceNode( + sourceFile, + targetNode, + createSatisfiesAsExpression( + getSynthesizedDeepClone(targetNode), + typeNode + ) + ); + } else { + Debug.assertNever(targetNode); + } + return [Diagnostics.Add_satisfies_and_an_inline_type_assertion_with_0, typeToStringForDiag(typeNode)]; + } + function extractAsVariable(span) { + const nodeWithDiag = getTokenAtPosition(sourceFile, span.start); + const targetNode = findBestFittingNode(nodeWithDiag, span); + if (!targetNode || isValueSignatureDeclaration(targetNode) || isValueSignatureDeclaration(targetNode.parent)) return; + const isExpressionTarget = isExpression(targetNode); + if (!isExpressionTarget) return; + if (isArrayLiteralExpression(targetNode)) { + changeTracker.replaceNode( + sourceFile, + targetNode, + createAsExpression(targetNode, factory.createTypeReferenceNode("const")) + ); + return [Diagnostics.Mark_array_literal_as_const]; + } + const parentPropertyAssignment = findAncestor(targetNode, isPropertyAssignment); + if (parentPropertyAssignment) { + if (parentPropertyAssignment === targetNode.parent && isEntityNameExpression(targetNode)) return; + const tempName = factory.createUniqueName( + getIdentifierForNode(targetNode, sourceFile, typeChecker, sourceFile), + 16 /* Optimistic */ + ); + let replacementTarget = targetNode; + let initializationNode = targetNode; + if (isSpreadElement(replacementTarget)) { + replacementTarget = walkUpParenthesizedExpressions(replacementTarget.parent); + if (isConstAssertion2(replacementTarget.parent)) { + initializationNode = replacementTarget = replacementTarget.parent; + } else { + initializationNode = createAsExpression( + replacementTarget, + factory.createTypeReferenceNode("const") + ); + } + } + if (isEntityNameExpression(replacementTarget)) return void 0; + const variableDefinition = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + tempName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializationNode + ) + ], 2 /* Const */) + ); + const statement = findAncestor(targetNode, isStatement); + changeTracker.insertNodeBefore(sourceFile, statement, variableDefinition); + changeTracker.replaceNode( + sourceFile, + replacementTarget, + factory.createAsExpression( + factory.cloneNode(tempName), + factory.createTypeQueryNode( + factory.cloneNode(tempName) + ) + ) + ); + return [Diagnostics.Extract_to_variable_and_replace_with_0_as_typeof_0, typeToStringForDiag(tempName)]; + } + } + function findExpandoFunction(node) { + const expandoDeclaration = findAncestor(node, (n) => isStatement(n) ? "quit" : isExpandoPropertyDeclaration(n)); + if (expandoDeclaration && isExpandoPropertyDeclaration(expandoDeclaration)) { + let assignmentTarget = expandoDeclaration; + if (isBinaryExpression(assignmentTarget)) { + assignmentTarget = assignmentTarget.left; + if (!isExpandoPropertyDeclaration(assignmentTarget)) return void 0; + } + const targetType = typeChecker.getTypeAtLocation(assignmentTarget.expression); + if (!targetType) return; + const properties = typeChecker.getPropertiesOfType(targetType); + if (some(properties, (p) => p.valueDeclaration === expandoDeclaration || p.valueDeclaration === expandoDeclaration.parent)) { + const fn = targetType.symbol.valueDeclaration; + if (fn) { + if (isFunctionExpressionOrArrowFunction(fn) && isVariableDeclaration(fn.parent)) { + return fn.parent; + } + if (isFunctionDeclaration(fn)) { + return fn; + } + } + } + } + return void 0; + } + function fixIsolatedDeclarationError(node) { + if (fixedNodes == null ? void 0 : fixedNodes.has(node)) return void 0; + fixedNodes == null ? void 0 : fixedNodes.add(node); + switch (node.kind) { + case 169 /* Parameter */: + case 172 /* PropertyDeclaration */: + case 260 /* VariableDeclaration */: + return addTypeToVariableLike(node); + case 219 /* ArrowFunction */: + case 218 /* FunctionExpression */: + case 262 /* FunctionDeclaration */: + case 174 /* MethodDeclaration */: + case 177 /* GetAccessor */: + return addTypeToSignatureDeclaration(node, sourceFile); + case 277 /* ExportAssignment */: + return transformExportAssignment(node); + case 263 /* ClassDeclaration */: + return transformExtendsClauseWithExpression(node); + case 206 /* ObjectBindingPattern */: + case 207 /* ArrayBindingPattern */: + return transformDestructuringPatterns(node); + default: + throw new Error(`Cannot find a fix for the given node ${node.kind}`); + } + } + function addTypeToSignatureDeclaration(func, sourceFile2) { + if (func.type) { + return; + } + const { typeNode } = inferType(func); + if (typeNode) { + changeTracker.tryInsertTypeAnnotation( + sourceFile2, + func, + typeNode + ); + return [Diagnostics.Add_return_type_0, typeToStringForDiag(typeNode)]; + } + } + function transformExportAssignment(defaultExport) { + if (defaultExport.isExportEquals) { + return; + } + const { typeNode } = inferType(defaultExport.expression); + if (!typeNode) return void 0; + const defaultIdentifier = factory.createUniqueName("_default"); + changeTracker.replaceNodeWithNodes(sourceFile, defaultExport, [ + factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + defaultIdentifier, + /*exclamationToken*/ + void 0, + typeNode, + defaultExport.expression + )], + 2 /* Const */ + ) + ), + factory.updateExportAssignment(defaultExport, defaultExport == null ? void 0 : defaultExport.modifiers, defaultIdentifier) + ]); + return [ + Diagnostics.Extract_default_export_to_variable + ]; + } + function transformExtendsClauseWithExpression(classDecl) { + var _a, _b; + const extendsClause = (_a = classDecl.heritageClauses) == null ? void 0 : _a.find((p) => p.token === 96 /* ExtendsKeyword */); + const heritageExpression = extendsClause == null ? void 0 : extendsClause.types[0]; + if (!heritageExpression) { + return void 0; + } + const { typeNode: heritageTypeNode } = inferType(heritageExpression.expression); + if (!heritageTypeNode) { + return void 0; + } + const baseClassName = factory.createUniqueName( + classDecl.name ? classDecl.name.text + "Base" : "Anonymous", + 16 /* Optimistic */ + ); + const heritageVariable = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + baseClassName, + /*exclamationToken*/ + void 0, + heritageTypeNode, + heritageExpression.expression + )], + 2 /* Const */ + ) + ); + changeTracker.insertNodeBefore(sourceFile, classDecl, heritageVariable); + const trailingComments = getTrailingCommentRanges(sourceFile.text, heritageExpression.end); + const realEnd = ((_b = trailingComments == null ? void 0 : trailingComments[trailingComments.length - 1]) == null ? void 0 : _b.end) ?? heritageExpression.end; + changeTracker.replaceRange( + sourceFile, + { + pos: heritageExpression.getFullStart(), + end: realEnd + }, + baseClassName, + { + prefix: " " + } + ); + return [Diagnostics.Extract_base_class_to_variable]; + } + let ExpressionType; + ((ExpressionType2) => { + ExpressionType2[ExpressionType2["Text"] = 0] = "Text"; + ExpressionType2[ExpressionType2["Computed"] = 1] = "Computed"; + ExpressionType2[ExpressionType2["ArrayAccess"] = 2] = "ArrayAccess"; + ExpressionType2[ExpressionType2["Identifier"] = 3] = "Identifier"; + })(ExpressionType || (ExpressionType = {})); + function transformDestructuringPatterns(bindingPattern) { + var _a; + const enclosingVariableDeclaration = bindingPattern.parent; + const enclosingVarStmt = bindingPattern.parent.parent.parent; + if (!enclosingVariableDeclaration.initializer) return void 0; + let baseExpr; + const newNodes = []; + if (!isIdentifier(enclosingVariableDeclaration.initializer)) { + const tempHolderForReturn = factory.createUniqueName("dest", 16 /* Optimistic */); + baseExpr = { expression: { kind: 3 /* Identifier */, identifier: tempHolderForReturn } }; + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + tempHolderForReturn, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + enclosingVariableDeclaration.initializer + )], + 2 /* Const */ + ) + )); + } else { + baseExpr = { expression: { kind: 3 /* Identifier */, identifier: enclosingVariableDeclaration.initializer } }; + } + const bindingElements = []; + if (isArrayBindingPattern(bindingPattern)) { + addArrayBindingPatterns(bindingPattern, bindingElements, baseExpr); + } else { + addObjectBindingPatterns(bindingPattern, bindingElements, baseExpr); + } + const expressionToVar = /* @__PURE__ */ new Map(); + for (const bindingElement of bindingElements) { + if (bindingElement.element.propertyName && isComputedPropertyName(bindingElement.element.propertyName)) { + const computedExpression = bindingElement.element.propertyName.expression; + const identifierForComputedProperty = factory.getGeneratedNameForNode(computedExpression); + const variableDecl = factory.createVariableDeclaration( + identifierForComputedProperty, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + computedExpression + ); + const variableList = factory.createVariableDeclarationList([variableDecl], 2 /* Const */); + const variableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + variableList + ); + newNodes.push(variableStatement); + expressionToVar.set(computedExpression, identifierForComputedProperty); + } + const name = bindingElement.element.name; + if (isArrayBindingPattern(name)) { + addArrayBindingPatterns(name, bindingElements, bindingElement); + } else if (isObjectBindingPattern(name)) { + addObjectBindingPatterns(name, bindingElements, bindingElement); + } else { + const { typeNode } = inferType(name); + let variableInitializer = createChainedExpression(bindingElement, expressionToVar); + if (bindingElement.element.initializer) { + const propertyName = (_a = bindingElement.element) == null ? void 0 : _a.propertyName; + const tempName = factory.createUniqueName( + propertyName && isIdentifier(propertyName) ? propertyName.text : "temp", + 16 /* Optimistic */ + ); + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + tempName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + variableInitializer + )], + 2 /* Const */ + ) + )); + variableInitializer = factory.createConditionalExpression( + factory.createBinaryExpression( + tempName, + factory.createToken(37 /* EqualsEqualsEqualsToken */), + factory.createIdentifier("undefined") + ), + factory.createToken(58 /* QuestionToken */), + bindingElement.element.initializer, + factory.createToken(59 /* ColonToken */), + variableInitializer + ); + } + const exportModifier = hasSyntacticModifier(enclosingVarStmt, 32 /* Export */) ? [factory.createToken(95 /* ExportKeyword */)] : void 0; + newNodes.push(factory.createVariableStatement( + exportModifier, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + typeNode, + variableInitializer + )], + 2 /* Const */ + ) + )); + } + } + if (enclosingVarStmt.declarationList.declarations.length > 1) { + newNodes.push(factory.updateVariableStatement( + enclosingVarStmt, + enclosingVarStmt.modifiers, + factory.updateVariableDeclarationList( + enclosingVarStmt.declarationList, + enclosingVarStmt.declarationList.declarations.filter((node) => node !== bindingPattern.parent) + ) + )); + } + changeTracker.replaceNodeWithNodes(sourceFile, enclosingVarStmt, newNodes); + return [ + Diagnostics.Extract_binding_expressions_to_variable + ]; + } + function addArrayBindingPatterns(bindingPattern, bindingElements, parent2) { + for (let i = 0; i < bindingPattern.elements.length; ++i) { + const element = bindingPattern.elements[i]; + if (isOmittedExpression(element)) { + continue; + } + bindingElements.push({ + element, + parent: parent2, + expression: { kind: 2 /* ArrayAccess */, arrayIndex: i } + }); + } + } + function addObjectBindingPatterns(bindingPattern, bindingElements, parent2) { + for (const bindingElement of bindingPattern.elements) { + let name; + if (bindingElement.propertyName) { + if (isComputedPropertyName(bindingElement.propertyName)) { + bindingElements.push({ + element: bindingElement, + parent: parent2, + expression: { kind: 1 /* Computed */, computed: bindingElement.propertyName.expression } + }); + continue; + } else { + name = bindingElement.propertyName.text; + } + } else { + name = bindingElement.name.text; + } + bindingElements.push({ + element: bindingElement, + parent: parent2, + expression: { kind: 0 /* Text */, text: name } + }); + } + } + function createChainedExpression(expression, expressionToVar) { + const reverseTraverse = [expression]; + while (expression.parent) { + expression = expression.parent; + reverseTraverse.push(expression); + } + let chainedExpression = reverseTraverse[reverseTraverse.length - 1].expression.identifier; + for (let i = reverseTraverse.length - 2; i >= 0; --i) { + const nextSubExpr = reverseTraverse[i].expression; + if (nextSubExpr.kind === 0 /* Text */) { + chainedExpression = factory.createPropertyAccessChain( + chainedExpression, + /*questionDotToken*/ + void 0, + factory.createIdentifier(nextSubExpr.text) + ); + } else if (nextSubExpr.kind === 1 /* Computed */) { + chainedExpression = factory.createElementAccessExpression( + chainedExpression, + expressionToVar.get(nextSubExpr.computed) + ); + } else if (nextSubExpr.kind === 2 /* ArrayAccess */) { + chainedExpression = factory.createElementAccessExpression( + chainedExpression, + nextSubExpr.arrayIndex + ); + } + } + return chainedExpression; + } + function inferType(node, variableType) { + if (typePrintMode === 1 /* Relative */) { + return relativeType(node); + } + let type = isValueSignatureDeclaration(node) ? tryGetReturnType2(node) : typeChecker.getTypeAtLocation(node); + if (!type) { + return emptyInferenceResult; + } + if (typePrintMode === 2 /* Widened */) { + if (variableType) { + type = variableType; + } + const widenedType = typeChecker.getWidenedLiteralType(type); + if (typeChecker.isTypeAssignableTo(widenedType, type)) { + return emptyInferenceResult; + } + type = widenedType; + } + if (isParameter(node) && typeChecker.requiresAddingImplicitUndefined(node)) { + type = typeChecker.getUnionType([typeChecker.getUndefinedType(), type], 0 /* None */); + } + const flags = (isVariableDeclaration(node) || isPropertyDeclaration(node) && hasSyntacticModifier(node, 256 /* Static */ | 8 /* Readonly */)) && type.flags & 8192 /* UniqueESSymbol */ ? 1048576 /* AllowUniqueESSymbolType */ : 0 /* None */; + return { + typeNode: typeToTypeNode2(type, findAncestor(node, isDeclaration) ?? sourceFile, flags), + mutatedTarget: false + }; + } + function createTypeOfFromEntityNameExpression(node) { + return factory.createTypeQueryNode(getSynthesizedDeepClone(node)); + } + function typeFromArraySpreadElements(node, name = "temp") { + const isConstContext = !!findAncestor(node, isConstAssertion2); + if (!isConstContext) return emptyInferenceResult; + return typeFromSpreads( + node, + name, + isConstContext, + (n) => n.elements, + isSpreadElement, + factory.createSpreadElement, + (props) => factory.createArrayLiteralExpression( + props, + /*multiLine*/ + true + ), + (types) => factory.createTupleTypeNode(types.map(factory.createRestTypeNode)) + ); + } + function typeFromObjectSpreadAssignment(node, name = "temp") { + const isConstContext = !!findAncestor(node, isConstAssertion2); + return typeFromSpreads( + node, + name, + isConstContext, + (n) => n.properties, + isSpreadAssignment, + factory.createSpreadAssignment, + (props) => factory.createObjectLiteralExpression( + props, + /*multiLine*/ + true + ), + factory.createIntersectionTypeNode + ); + } + function typeFromSpreads(node, name, isConstContext, getChildren, isSpread, createSpread, makeNodeOfKind, finalType) { + const intersectionTypes = []; + const newSpreads = []; + let currentVariableProperties; + const statement = findAncestor(node, isStatement); + for (const prop of getChildren(node)) { + if (isSpread(prop)) { + finalizesVariablePart(); + if (isEntityNameExpression(prop.expression)) { + intersectionTypes.push(createTypeOfFromEntityNameExpression(prop.expression)); + newSpreads.push(prop); + } else { + makeVariable(prop.expression); + } + } else { + (currentVariableProperties ?? (currentVariableProperties = [])).push(prop); + } + } + if (newSpreads.length === 0) { + return emptyInferenceResult; + } + finalizesVariablePart(); + changeTracker.replaceNode(sourceFile, node, makeNodeOfKind(newSpreads)); + return { + typeNode: finalType(intersectionTypes), + mutatedTarget: true + }; + function makeVariable(expression) { + const tempName = factory.createUniqueName( + name + "_Part" + (newSpreads.length + 1), + 16 /* Optimistic */ + ); + const initializer = !isConstContext ? expression : factory.createAsExpression( + expression, + factory.createTypeReferenceNode("const") + ); + const variableDefinition = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([ + factory.createVariableDeclaration( + tempName, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + initializer + ) + ], 2 /* Const */) + ); + changeTracker.insertNodeBefore(sourceFile, statement, variableDefinition); + intersectionTypes.push(createTypeOfFromEntityNameExpression(tempName)); + newSpreads.push(createSpread(tempName)); + } + function finalizesVariablePart() { + if (currentVariableProperties) { + makeVariable(makeNodeOfKind( + currentVariableProperties + )); + currentVariableProperties = void 0; + } + } + } + function isConstAssertion2(location) { + return isAssertionExpression(location) && isConstTypeReference(location.type); + } + function relativeType(node) { + if (isParameter(node)) { + return emptyInferenceResult; + } + if (isShorthandPropertyAssignment(node)) { + return { + typeNode: createTypeOfFromEntityNameExpression(node.name), + mutatedTarget: false + }; + } + if (isEntityNameExpression(node)) { + return { + typeNode: createTypeOfFromEntityNameExpression(node), + mutatedTarget: false + }; + } + if (isConstAssertion2(node)) { + return relativeType(node.expression); + } + if (isArrayLiteralExpression(node)) { + const variableDecl = findAncestor(node, isVariableDeclaration); + const partName = variableDecl && isIdentifier(variableDecl.name) ? variableDecl.name.text : void 0; + return typeFromArraySpreadElements(node, partName); + } + if (isObjectLiteralExpression(node)) { + const variableDecl = findAncestor(node, isVariableDeclaration); + const partName = variableDecl && isIdentifier(variableDecl.name) ? variableDecl.name.text : void 0; + return typeFromObjectSpreadAssignment(node, partName); + } + if (isVariableDeclaration(node) && node.initializer) { + return relativeType(node.initializer); + } + if (isConditionalExpression(node)) { + const { typeNode: trueType, mutatedTarget: mTrue } = relativeType(node.whenTrue); + if (!trueType) return emptyInferenceResult; + const { typeNode: falseType, mutatedTarget: mFalse } = relativeType(node.whenFalse); + if (!falseType) return emptyInferenceResult; + return { + typeNode: factory.createUnionTypeNode([trueType, falseType]), + mutatedTarget: mTrue || mFalse + }; + } + return emptyInferenceResult; + } + function typeToTypeNode2(type, enclosingDeclaration, flags = 0 /* None */) { + let isTruncated = false; + const result2 = typeToAutoImportableTypeNode(typeChecker, importAdder, type, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, { + moduleResolverHost: program, + trackSymbol() { + return true; + }, + reportTruncationError() { + isTruncated = true; + } + }); + return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2; + } + function tryGetReturnType2(node) { + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) { + return typeChecker.getReturnTypeOfSignature(signature); + } + } + function addTypeToVariableLike(decl) { + const { typeNode } = inferType(decl); + if (typeNode) { + if (decl.type) { + changeTracker.replaceNode(getSourceFileOfNode(decl), decl.type, typeNode); + } else { + changeTracker.tryInsertTypeAnnotation(getSourceFileOfNode(decl), decl, typeNode); + } + return [Diagnostics.Add_annotation_of_type_0, typeToStringForDiag(typeNode)]; + } + } + function typeToStringForDiag(node) { + setEmitFlags(node, 1 /* SingleLine */); + const result2 = typePrinter.printNode(4 /* Unspecified */, node, sourceFile); + if (result2.length > defaultMaximumTruncationLength) { + return result2.substring(0, defaultMaximumTruncationLength - "...".length) + "..."; + } + setEmitFlags(node, 0 /* None */); + return result2; + } + function findAncestorWithMissingType(node) { + return findAncestor(node, (n) => { + return canHaveTypeAnnotation.has(n.kind) && (!isObjectBindingPattern(n) && !isArrayBindingPattern(n) || isVariableDeclaration(n.parent)); + }); + } + function findBestFittingNode(node, span) { + while (node && node.end < span.start + span.length) { + node = node.parent; + } + while (node.parent.pos === node.pos && node.parent.end === node.end) { + node = node.parent; + } + if (isIdentifier(node) && hasInitializer(node.parent) && node.parent.initializer) { + return node.parent.initializer; + } + return node; + } +} + +// src/services/codefixes/fixAwaitInSyncFunction.ts +var fixId37 = "fixAwaitInSyncFunction"; +var errorCodes48 = [ Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code ]; registerCodeFix({ - errorCodes: errorCodes47, + errorCodes: errorCodes48, getCodeActions(context) { const { sourceFile, span } = context; const nodes = getNodes3(sourceFile, span.start); - if (!nodes) - return void 0; + if (!nodes) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, nodes)); - return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)]; + return [createCodeFixAction(fixId37, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId37, Diagnostics.Add_all_missing_async_modifiers)]; }, - fixIds: [fixId36], + fixIds: [fixId37], getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { const seen = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes47, (changes, diag2) => { + return codeFixAll(context, errorCodes48, (changes, diag2) => { const nodes = getNodes3(diag2.file, diag2.start); - if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) - return; + if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; doChange31(changes, context.sourceFile, nodes); }); } @@ -159264,21 +159523,21 @@ function doChange31(changes, sourceFile, { insertBefore, returnType }) { } // src/services/codefixes/fixPropertyOverrideAccessor.ts -var errorCodes48 = [ +var errorCodes49 = [ Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code ]; -var fixId37 = "fixPropertyOverrideAccessor"; +var fixId38 = "fixPropertyOverrideAccessor"; registerCodeFix({ - errorCodes: errorCodes48, + errorCodes: errorCodes49, getCodeActions(context) { const edits = doChange32(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); if (edits) { - return [createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; + return [createCodeFixAction(fixId38, edits, Diagnostics.Generate_get_and_set_accessors, fixId38, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; } }, - fixIds: [fixId37], - getAllCodeActions: (context) => codeFixAll(context, errorCodes48, (changes, diag2) => { + fixIds: [fixId38], + getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { const edits = doChange32(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { @@ -159300,12 +159559,10 @@ function doChange32(file, start, length2, code, context) { const containingClass = node.parent; Debug.assert(isClassLike(containingClass), "erroneous accessors should only be inside classes"); const base = singleOrUndefined(getAllSupers(containingClass, checker)); - if (!base) - return []; + if (!base) return []; const name = unescapeLeadingUnderscores(getTextOfPropertyName(node.name)); const baseProp = checker.getPropertyOfType(checker.getTypeAtLocation(base), name); - if (!baseProp || !baseProp.valueDeclaration) - return []; + if (!baseProp || !baseProp.valueDeclaration) return []; startPosition = baseProp.valueDeclaration.pos; endPosition = baseProp.valueDeclaration.end; file = getSourceFileOfNode(baseProp.valueDeclaration); @@ -159316,8 +159573,8 @@ function doChange32(file, start, length2, code, context) { } // src/services/codefixes/inferFromUsage.ts -var fixId38 = "inferFromUsage"; -var errorCodes49 = [ +var fixId39 = "inferFromUsage"; +var errorCodes50 = [ // Variable declarations Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, // Variable uses @@ -159351,7 +159608,7 @@ var errorCodes49 = [ Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code ]; registerCodeFix({ - errorCodes: errorCodes49, + errorCodes: errorCodes50, getCodeActions(context) { const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context; const token = getTokenAtPosition(sourceFile, start); @@ -159371,13 +159628,13 @@ registerCodeFix({ ); }); const name = declaration && getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId38, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId38, Diagnostics.Infer_all_types_from_usage)]; + return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId39, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId39, Diagnostics.Infer_all_types_from_usage)]; }, - fixIds: [fixId38], + fixIds: [fixId39], getAllCodeActions(context) { const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); - return codeFixAll(context, errorCodes49, (changes, err) => { + return codeFixAll(context, errorCodes50, (changes, err) => { doChange33(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); } @@ -159518,15 +159775,13 @@ function annotateParameters(changes, importAdder, sourceFile, parameterDeclarati annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { const needParens = isArrowFunction(containingFunction) && !findChildOfKind(containingFunction, 21 /* OpenParenToken */, sourceFile); - if (needParens) - changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */)); + if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), factory.createToken(21 /* OpenParenToken */)); for (const { declaration, type } of parameterInferences) { if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, importAdder, sourceFile, declaration, type, program, host); } } - if (needParens) - changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */)); + if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), factory.createToken(22 /* CloseParenToken */)); } } function annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken) { @@ -160046,8 +160301,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { return combineTypes(inferTypes(usage)); } function combineTypes(inferences) { - if (!inferences.length) - return checker.getAnyType(); + if (!inferences.length) return checker.getAnyType(); const stringNumber = checker.getUnionType([checker.getStringType(), checker.getNumberType()]); const priorities = [ { @@ -160106,10 +160360,8 @@ function inferTypeFromReferences(program, references, cancellationToken) { return [name, s]; }); const indexInfos = []; - if (stringIndices.length) - indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); - if (numberIndices.length) - indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); + if (stringIndices.length) indexInfos.push(checker.createIndexInfo(checker.getStringType(), checker.getUnionType(stringIndices), stringIndexReadonly)); + if (numberIndices.length) indexInfos.push(checker.createIndexInfo(checker.getNumberType(), checker.getUnionType(numberIndices), numberIndexReadonly)); return checker.createAnonymousType( anons[0].symbol, members, @@ -160178,8 +160430,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { ); } function inferNamedTypesFromProperties(usage) { - if (!usage.properties || !usage.properties.size) - return []; + if (!usage.properties || !usage.properties.size) return []; const types = builtins.filter((t) => allPropertiesAreAssignableToUsage(t, usage)); if (0 < types.length && types.length < 3) { return types.map((t) => inferInstantiationFromUsage(t, usage)); @@ -160187,8 +160438,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { return []; } function allPropertiesAreAssignableToUsage(type, usage) { - if (!usage.properties) - return false; + if (!usage.properties) return false; return !forEachEntry(usage.properties, (propUsage, name) => { const source = checker.getTypeOfPropertyOfType(type, name); if (!source) { @@ -160208,8 +160458,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { } const generic = type.target; const singleTypeParameter = singleOrUndefined(generic.typeParameters); - if (!singleTypeParameter) - return type; + if (!singleTypeParameter) return type; const types = []; usage.properties.forEach((propUsage, name) => { const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name); @@ -160316,13 +160565,13 @@ function inferTypeFromReferences(program, references, cancellationToken) { } // src/services/codefixes/fixReturnTypeInAsyncFunction.ts -var fixId39 = "fixReturnTypeInAsyncFunction"; -var errorCodes50 = [ +var fixId40 = "fixReturnTypeInAsyncFunction"; +var errorCodes51 = [ Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code ]; registerCodeFix({ - errorCodes: errorCodes50, - fixIds: [fixId39], + errorCodes: errorCodes51, + fixIds: [fixId40], getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { const { sourceFile, program, span } = context; const checker = program.getTypeChecker(); @@ -160333,14 +160582,14 @@ registerCodeFix({ const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( - fixId39, + fixId40, changes, [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], - fixId39, + fixId40, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions )]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes50, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes51, (changes, diag2) => { const info = getInfo16(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { doChange34(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); @@ -160376,13 +160625,13 @@ function doChange34(changes, sourceFile, returnTypeNode, promisedTypeNode) { // src/services/codefixes/disableJsDiagnostics.ts var fixName4 = "disableJsDiagnostics"; -var fixId40 = "disableJsDiagnostics"; -var errorCodes51 = mapDefined(Object.keys(Diagnostics), (key) => { +var fixId41 = "disableJsDiagnostics"; +var errorCodes52 = mapDefined(Object.keys(Diagnostics), (key) => { const diag2 = Diagnostics[key]; return diag2.category === 1 /* Error */ ? diag2.code : void 0; }); registerCodeFix({ - errorCodes: errorCodes51, + errorCodes: errorCodes52, getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { const { sourceFile, program, span, host, formatContext } = context; if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { @@ -160403,14 +160652,14 @@ registerCodeFix({ ) ]; if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) { - fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId40, Diagnostics.Add_ts_ignore_to_all_error_messages)); + fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId41, Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; }, - fixIds: [fixId40], + fixIds: [fixId41], getAllCodeActions: (context) => { const seenLines = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes51, (changes, diag2) => { + return codeFixAll(context, errorCodes52, (changes, diag2) => { if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) { makeChange8(changes, diag2.file, diag2.start, seenLines); } @@ -160476,7 +160725,8 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con switch (kind) { case 171 /* PropertySignature */: case 172 /* PropertyDeclaration */: - const flags = quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : void 0; + let flags = 1 /* NoTruncation */; + flags |= quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0; let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); @@ -160572,8 +160822,7 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con } function outputMethod(quotePreference2, signature, modifiers2, name, body2) { const method = createSignatureDeclarationFromSignature(174 /* MethodDeclaration */, context, quotePreference2, signature, body2, name, modifiers2, optional && !!(preserveOptional & 1 /* Method */), enclosingDeclaration, importAdder); - if (method) - addClassElement(method); + if (method) addClassElement(method); } function createModifiers() { let modifiers2; @@ -160638,7 +160887,7 @@ function createSignatureDeclarationFromSignature(kind, context, quotePreference, } let typeParameters = isJs ? void 0 : signatureDeclaration.typeParameters; let parameters = signatureDeclaration.parameters; - let type = isJs ? void 0 : signatureDeclaration.type; + let type = isJs ? void 0 : getSynthesizedDeepClone(signatureDeclaration.type); if (importAdder) { if (typeParameters) { const newTypeParameters = sameMap(typeParameters, (typeParameterDecl) => { @@ -160995,8 +161244,7 @@ function createStubbedBody(text, quotePreference) { } function setJsonCompilerOptionValues(changeTracker, configFile, options) { const tsconfigObjectLiteral = getTsConfigObjectLiteralExpression(configFile); - if (!tsconfigObjectLiteral) - return void 0; + if (!tsconfigObjectLiteral) return void 0; const compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === void 0) { changeTracker.insertNodeAtObjectStart( @@ -161083,8 +161331,7 @@ function findAncestorMatchingSpan(sourceFile, span) { // src/services/codefixes/generateAccessors.ts function generateAccessorFromProperty(file, program, start, end, context, _actionName) { const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end); - if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo)) - return void 0; + if (!fieldInfo || ts_refactor_exports.isRefactorErrorInfo(fieldInfo)) return void 0; const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); const { isStatic: isStatic2, isReadonly, fieldName, accessorName, originalName, type, container, declaration } = fieldInfo; suppressLeadingAndTrailingTrivia(fieldName); @@ -161245,8 +161492,7 @@ function updatePropertyDeclaration(changeTracker, file, declaration, type, field function updatePropertyAssignmentDeclaration(changeTracker, file, declaration, fieldName) { let assignment = factory.updatePropertyAssignment(declaration, fieldName, declaration.initializer); if (assignment.modifiers || assignment.questionToken || assignment.exclamationToken) { - if (assignment === declaration) - assignment = factory.cloneNode(assignment); + if (assignment === declaration) assignment = factory.cloneNode(assignment); assignment.modifiers = void 0; assignment.questionToken = void 0; assignment.exclamationToken = void 0; @@ -161266,8 +161512,7 @@ function insertAccessor(changeTracker, file, accessor, declaration, container) { isParameterPropertyDeclaration(declaration, declaration.parent) ? changeTracker.insertMemberAtStart(file, container, accessor) : isPropertyAssignment(declaration) ? changeTracker.insertNodeAfterComma(file, declaration, accessor) : changeTracker.insertNodeAfter(file, declaration, accessor); } function updateReadonlyPropertyInitializerStatementConstructor(changeTracker, file, constructor, fieldName, originalName) { - if (!constructor.body) - return; + if (!constructor.body) return; constructor.body.forEachChild(function recur(node) { if (isElementAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && isStringLiteral(node.argumentExpression) && node.argumentExpression.text === originalName && isWriteAccess(node)) { changeTracker.replaceNode(file, node.argumentExpression, factory.createStringLiteral(fieldName)); @@ -161297,12 +161542,10 @@ function getAllSupers(decl, checker) { while (decl) { const superElement = getClassExtendsHeritageElement(decl); const superSymbol = superElement && checker.getSymbolAtLocation(superElement.expression); - if (!superSymbol) - break; + if (!superSymbol) break; const symbol = superSymbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(superSymbol) : superSymbol; const superDecl = symbol.declarations && find(symbol.declarations, isClassLike); - if (!superDecl) - break; + if (!superDecl) break; res.push(superDecl); decl = superDecl; } @@ -161409,13 +161652,12 @@ var fixName6 = "strictClassInitialization"; var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; var fixIdAddInitializer = "addMissingPropertyInitializer"; -var errorCodes52 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; +var errorCodes53 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; registerCodeFix({ - errorCodes: errorCodes52, + errorCodes: errorCodes53, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { const info = getInfo17(context.sourceFile, context.span.start); - if (!info) - return; + if (!info) return; const result = []; append(result, getActionForAddMissingUndefinedType(context, info)); append(result, getActionForAddMissingDefiniteAssignmentAssertion(context, info)); @@ -161424,10 +161666,9 @@ registerCodeFix({ }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes52, (changes, diag2) => { + return codeFixAll(context, errorCodes53, (changes, diag2) => { const info = getInfo17(diag2.file, diag2.start); - if (!info) - return; + if (!info) return; switch (context.fixId) { case fixIdAddDefiniteAssignmentAssertions: addDefiniteAssignmentAssertion(changes, diag2.file, info.prop); @@ -161438,8 +161679,7 @@ registerCodeFix({ case fixIdAddInitializer: const checker = context.program.getTypeChecker(); const initializer = getInitializer(checker, info.prop); - if (!initializer) - return; + if (!initializer) return; addInitializer(changes, diag2.file, info.prop, initializer); break; default: @@ -161459,8 +161699,7 @@ function getInfo17(sourceFile, pos) { return void 0; } function getActionForAddMissingDefiniteAssignmentAssertion(context, info) { - if (info.isJs) - return void 0; + if (info.isJs) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addDefiniteAssignmentAssertion(t, context.sourceFile, info.prop)); return createCodeFixAction(fixName6, changes, [Diagnostics.Add_definite_assignment_assertion_to_property_0, info.prop.getText()], fixIdAddDefiniteAssignmentAssertions, Diagnostics.Add_definite_assignment_assertions_to_all_uninitialized_properties); } @@ -161495,12 +161734,10 @@ function addUndefinedType(changeTracker, sourceFile, info) { } } function getActionForAddMissingInitializer(context, info) { - if (info.isJs) - return void 0; + if (info.isJs) return void 0; const checker = context.program.getTypeChecker(); const initializer = getInitializer(checker, info.prop); - if (!initializer) - return void 0; + if (!initializer) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addInitializer(t, context.sourceFile, info.prop, initializer)); return createCodeFixAction(fixName6, changes, [Diagnostics.Add_initializer_to_property_0, info.prop.name.getText()], fixIdAddInitializer, Diagnostics.Add_initializers_to_all_uninitialized_properties); } @@ -161535,11 +161772,9 @@ function getDefaultValueFromType(checker, type) { return firstDefined(type.types, (t) => getDefaultValueFromType(checker, t)); } else if (type.isClass()) { const classDeclaration = getClassLikeDeclarationOfSymbol(type.symbol); - if (!classDeclaration || hasSyntacticModifier(classDeclaration, 64 /* Abstract */)) - return void 0; + if (!classDeclaration || hasSyntacticModifier(classDeclaration, 64 /* Abstract */)) return void 0; const constructorDeclaration = getFirstConstructorWithBody(classDeclaration); - if (constructorDeclaration && constructorDeclaration.parameters.length) - return void 0; + if (constructorDeclaration && constructorDeclaration.parameters.length) return void 0; return factory.createNewExpression( factory.createIdentifier(type.symbol.name), /*typeArguments*/ @@ -161554,20 +161789,20 @@ function getDefaultValueFromType(checker, type) { } // src/services/codefixes/requireInTs.ts -var fixId41 = "requireInTs"; -var errorCodes53 = [Diagnostics.require_call_may_be_converted_to_an_import.code]; +var fixId42 = "requireInTs"; +var errorCodes54 = [Diagnostics.require_call_may_be_converted_to_an_import.code]; registerCodeFix({ - errorCodes: errorCodes53, + errorCodes: errorCodes54, getCodeActions(context) { const info = getInfo18(context.sourceFile, context.program, context.span.start); if (!info) { return void 0; } const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, context.sourceFile, info)); - return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)]; + return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_require_to_import, fixId42, Diagnostics.Convert_all_require_to_import)]; }, - fixIds: [fixId41], - getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => { + fixIds: [fixId42], + getAllCodeActions: (context) => codeFixAll(context, errorCodes54, (changes, diag2) => { const info = getInfo18(diag2.file, context.program, diag2.start); if (info) { doChange35(changes, context.sourceFile, info); @@ -161642,29 +161877,26 @@ function tryCreateNamedImportsFromObjectBindingPattern(node) { } // src/services/codefixes/useDefaultImport.ts -var fixId42 = "useDefaultImport"; -var errorCodes54 = [Diagnostics.Import_may_be_converted_to_a_default_import.code]; +var fixId43 = "useDefaultImport"; +var errorCodes55 = [Diagnostics.Import_may_be_converted_to_a_default_import.code]; registerCodeFix({ - errorCodes: errorCodes54, + errorCodes: errorCodes55, getCodeActions(context) { const { sourceFile, span: { start } } = context; const info = getInfo19(sourceFile, start); - if (!info) - return void 0; + if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, info, context.preferences)); - return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)]; + return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_default_import, fixId43, Diagnostics.Convert_all_to_default_imports)]; }, - fixIds: [fixId42], - getAllCodeActions: (context) => codeFixAll(context, errorCodes54, (changes, diag2) => { + fixIds: [fixId43], + getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => { const info = getInfo19(diag2.file, diag2.start); - if (info) - doChange36(changes, diag2.file, info, context.preferences); + if (info) doChange36(changes, diag2.file, info, context.preferences); }) }); function getInfo19(sourceFile, pos) { const name = getTokenAtPosition(sourceFile, pos); - if (!isIdentifier(name)) - return void 0; + if (!isIdentifier(name)) return void 0; const { parent: parent2 } = name; if (isImportEqualsDeclaration(parent2) && isExternalModuleReference(parent2.moduleReference)) { return { importNode: parent2, name, moduleSpecifier: parent2.moduleReference.expression }; @@ -161684,21 +161916,21 @@ function doChange36(changes, sourceFile, info, preferences) { } // src/services/codefixes/useBigintLiteral.ts -var fixId43 = "useBigintLiteral"; -var errorCodes55 = [ +var fixId44 = "useBigintLiteral"; +var errorCodes56 = [ Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code ]; registerCodeFix({ - errorCodes: errorCodes55, + errorCodes: errorCodes56, getCodeActions: function getCodeActionsToUseBigintLiteral(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, context.sourceFile, context.span)); if (changes.length > 0) { - return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId43, Diagnostics.Convert_all_to_bigint_numeric_literals)]; + return [createCodeFixAction(fixId44, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId44, Diagnostics.Convert_all_to_bigint_numeric_literals)]; } }, - fixIds: [fixId43], + fixIds: [fixId44], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes55, (changes, diag2) => makeChange9(changes, diag2.file, diag2)); + return codeFixAll(context, errorCodes56, (changes, diag2) => makeChange9(changes, diag2.file, diag2)); } }); function makeChange9(changeTracker, sourceFile, span) { @@ -161712,18 +161944,18 @@ function makeChange9(changeTracker, sourceFile, span) { // src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; -var fixId44 = fixIdAddMissingTypeof; -var errorCodes56 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; +var fixId45 = fixIdAddMissingTypeof; +var errorCodes57 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; registerCodeFix({ - errorCodes: errorCodes56, + errorCodes: errorCodes57, getCodeActions: function getCodeActionsToAddMissingTypeof(context) { const { sourceFile, span } = context; const importType = getImportTypeNode(sourceFile, span.start); const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, importType)); - return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)]; + return [createCodeFixAction(fixId45, changes, Diagnostics.Add_missing_typeof, fixId45, Diagnostics.Add_missing_typeof)]; }, - fixIds: [fixId44], - getAllCodeActions: (context) => codeFixAll(context, errorCodes56, (changes, diag2) => doChange37(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + fixIds: [fixId45], + getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => doChange37(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); function getImportTypeNode(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -161746,22 +161978,20 @@ function doChange37(changes, sourceFile, importType) { // src/services/codefixes/wrapJsxInFragment.ts var fixID2 = "wrapJsxInFragment"; -var errorCodes57 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code]; +var errorCodes58 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code]; registerCodeFix({ - errorCodes: errorCodes57, + errorCodes: errorCodes58, getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { const { sourceFile, span } = context; const node = findNodeToFix(sourceFile, span.start); - if (!node) - return void 0; + if (!node) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, node)); return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], - getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes58, (changes, diag2) => { const node = findNodeToFix(context.sourceFile, diag2.start); - if (!node) - return void 0; + if (!node) return void 0; doChange38(changes, context.sourceFile, node); }) }); @@ -161771,17 +162001,14 @@ function findNodeToFix(sourceFile, pos) { let binaryExpr = firstJsxElementOrOpenElement.parent; if (!isBinaryExpression(binaryExpr)) { binaryExpr = binaryExpr.parent; - if (!isBinaryExpression(binaryExpr)) - return void 0; + if (!isBinaryExpression(binaryExpr)) return void 0; } - if (!nodeIsMissing(binaryExpr.operatorToken)) - return void 0; + if (!nodeIsMissing(binaryExpr.operatorToken)) return void 0; return binaryExpr; } function doChange38(changeTracker, sf, node) { const jsx = flattenInvalidBinaryExpr(node); - if (jsx) - changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); + if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); } function flattenInvalidBinaryExpr(node) { const children = []; @@ -161795,24 +162022,22 @@ function flattenInvalidBinaryExpr(node) { } else if (isBinaryExpression(current.right)) { current = current.right; continue; - } else - return void 0; - } else - return void 0; + } else return void 0; + } else return void 0; } } // src/services/codefixes/wrapDecoratorInParentheses.ts -var fixId45 = "wrapDecoratorInParentheses"; -var errorCodes58 = [Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator.code]; +var fixId46 = "wrapDecoratorInParentheses"; +var errorCodes59 = [Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator.code]; registerCodeFix({ - errorCodes: errorCodes58, + errorCodes: errorCodes59, getCodeActions: function getCodeActionsToWrapDecoratorExpressionInParentheses(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span.start)); - return [createCodeFixAction(fixId45, changes, Diagnostics.Wrap_in_parentheses, fixId45, Diagnostics.Wrap_all_invalid_decorator_expressions_in_parentheses)]; + return [createCodeFixAction(fixId46, changes, Diagnostics.Wrap_in_parentheses, fixId46, Diagnostics.Wrap_all_invalid_decorator_expressions_in_parentheses)]; }, - fixIds: [fixId45], - getAllCodeActions: (context) => codeFixAll(context, errorCodes58, (changes, diag2) => makeChange10(changes, diag2.file, diag2.start)) + fixIds: [fixId46], + getAllCodeActions: (context) => codeFixAll(context, errorCodes59, (changes, diag2) => makeChange10(changes, diag2.file, diag2.start)) }); function makeChange10(changeTracker, sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -161823,34 +162048,30 @@ function makeChange10(changeTracker, sourceFile, pos) { } // src/services/codefixes/convertToMappedObjectType.ts -var fixId46 = "fixConvertToMappedObjectType"; -var errorCodes59 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; +var fixId47 = "fixConvertToMappedObjectType"; +var errorCodes60 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; registerCodeFix({ - errorCodes: errorCodes59, + errorCodes: errorCodes60, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { const { sourceFile, span } = context; const info = getInfo20(sourceFile, span.start); - if (!info) - return void 0; + if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info)); const name = idText(info.container.name); - return [createCodeFixAction(fixId46, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId46, [Diagnostics.Convert_0_to_mapped_object_type, name])]; + return [createCodeFixAction(fixId47, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId47, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, - fixIds: [fixId46], - getAllCodeActions: (context) => codeFixAll(context, errorCodes59, (changes, diag2) => { + fixIds: [fixId47], + getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, diag2) => { const info = getInfo20(diag2.file, diag2.start); - if (info) - doChange39(changes, diag2.file, info); + if (info) doChange39(changes, diag2.file, info); }) }); function getInfo20(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); - if (!indexSignature) - return void 0; + if (!indexSignature) return void 0; const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent : tryCast(indexSignature.parent.parent, isTypeAliasDeclaration); - if (!container) - return void 0; + if (!container) return void 0; return { indexSignature, container }; } function createTypeAliasFromInterface(declaration, type) { @@ -161885,12 +162106,12 @@ function doChange39(changes, sourceFile, { indexSignature, container }) { } // src/services/codefixes/removeAccidentalCallParentheses.ts -var fixId47 = "removeAccidentalCallParentheses"; -var errorCodes60 = [ +var fixId48 = "removeAccidentalCallParentheses"; +var errorCodes61 = [ Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code ]; registerCodeFix({ - errorCodes: errorCodes60, + errorCodes: errorCodes61, getCodeActions(context) { const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression); if (!callExpression) { @@ -161899,27 +162120,27 @@ registerCodeFix({ const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { t.deleteRange(context.sourceFile, { pos: callExpression.expression.end, end: callExpression.end }); }); - return [createCodeFixActionWithoutFixAll(fixId47, changes, Diagnostics.Remove_parentheses)]; + return [createCodeFixActionWithoutFixAll(fixId48, changes, Diagnostics.Remove_parentheses)]; }, - fixIds: [fixId47] + fixIds: [fixId48] }); // src/services/codefixes/removeUnnecessaryAwait.ts -var fixId48 = "removeUnnecessaryAwait"; -var errorCodes61 = [ +var fixId49 = "removeUnnecessaryAwait"; +var errorCodes62 = [ Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code ]; registerCodeFix({ - errorCodes: errorCodes61, + errorCodes: errorCodes62, getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span)); if (changes.length > 0) { - return [createCodeFixAction(fixId48, changes, Diagnostics.Remove_unnecessary_await, fixId48, Diagnostics.Remove_all_unnecessary_uses_of_await)]; + return [createCodeFixAction(fixId49, changes, Diagnostics.Remove_unnecessary_await, fixId49, Diagnostics.Remove_all_unnecessary_uses_of_await)]; } }, - fixIds: [fixId48], + fixIds: [fixId49], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes61, (changes, diag2) => makeChange11(changes, diag2.file, diag2)); + return codeFixAll(context, errorCodes62, (changes, diag2) => makeChange11(changes, diag2.file, diag2)); } }); function makeChange11(changeTracker, sourceFile, span) { @@ -161947,20 +162168,20 @@ function makeChange11(changeTracker, sourceFile, span) { } // src/services/codefixes/splitTypeOnlyImport.ts -var errorCodes62 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; -var fixId49 = "splitTypeOnlyImport"; +var errorCodes63 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; +var fixId50 = "splitTypeOnlyImport"; registerCodeFix({ - errorCodes: errorCodes62, - fixIds: [fixId49], + errorCodes: errorCodes63, + fixIds: [fixId50], getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context); }); if (changes.length) { - return [createCodeFixAction(fixId49, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId49, Diagnostics.Split_all_invalid_type_only_imports)]; + return [createCodeFixAction(fixId50, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId50, Diagnostics.Split_all_invalid_type_only_imports)]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, error2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes63, (changes, error2) => { splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error2), context); }) }); @@ -162009,23 +162230,22 @@ function splitTypeOnlyImport(changes, importDeclaration, context) { } // src/services/codefixes/convertConstToLet.ts -var fixId50 = "fixConvertConstToLet"; -var errorCodes63 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; +var fixId51 = "fixConvertConstToLet"; +var errorCodes64 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; registerCodeFix({ - errorCodes: errorCodes63, + errorCodes: errorCodes64, getCodeActions: function getCodeActionsToConvertConstToLet(context) { const { sourceFile, span, program } = context; const info = getInfo21(sourceFile, span.start, program); - if (info === void 0) - return; + if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info.token)); - return [createCodeFixActionMaybeFixAll(fixId50, changes, Diagnostics.Convert_const_to_let, fixId50, Diagnostics.Convert_all_const_to_let)]; + return [createCodeFixActionMaybeFixAll(fixId51, changes, Diagnostics.Convert_const_to_let, fixId51, Diagnostics.Convert_all_const_to_let)]; }, getAllCodeActions: (context) => { const { program } = context; const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes63, (diag2) => { + eachDiagnostic(context, errorCodes64, (diag2) => { const info = getInfo21(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { @@ -162036,20 +162256,17 @@ registerCodeFix({ }); })); }, - fixIds: [fixId50] + fixIds: [fixId51] }); function getInfo21(sourceFile, pos, program) { var _a; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); - if (symbol === void 0) - return; + if (symbol === void 0) return; const declaration = tryCast((_a = symbol == null ? void 0 : symbol.valueDeclaration) == null ? void 0 : _a.parent, isVariableDeclarationList); - if (declaration === void 0) - return; + if (declaration === void 0) return; const constToken = findChildOfKind(declaration, 87 /* ConstKeyword */, sourceFile); - if (constToken === void 0) - return; + if (constToken === void 0) return; return { symbol, token: constToken }; } function doChange40(changes, sourceFile, token) { @@ -162057,30 +162274,28 @@ function doChange40(changes, sourceFile, token) { } // src/services/codefixes/fixExpectedComma.ts -var fixId51 = "fixExpectedComma"; +var fixId52 = "fixExpectedComma"; var expectedErrorCode = Diagnostics._0_expected.code; -var errorCodes64 = [expectedErrorCode]; +var errorCodes65 = [expectedErrorCode]; registerCodeFix({ - errorCodes: errorCodes64, + errorCodes: errorCodes65, getCodeActions(context) { const { sourceFile } = context; const info = getInfo22(sourceFile, context.span.start, context.errorCode); - if (!info) - return void 0; + if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange41(t, sourceFile, info)); return [createCodeFixAction( - fixId51, + fixId52, changes, [Diagnostics.Change_0_to_1, ";", ","], - fixId51, + fixId52, [Diagnostics.Change_0_to_1, ";", ","] )]; }, - fixIds: [fixId51], - getAllCodeActions: (context) => codeFixAll(context, errorCodes64, (changes, diag2) => { + fixIds: [fixId52], + getAllCodeActions: (context) => codeFixAll(context, errorCodes65, (changes, diag2) => { const info = getInfo22(diag2.file, diag2.start, diag2.code); - if (info) - doChange41(changes, context.sourceFile, info); + if (info) doChange41(changes, context.sourceFile, info); }) }); function getInfo22(sourceFile, pos, _) { @@ -162094,35 +162309,32 @@ function doChange41(changes, sourceFile, { node }) { // src/services/codefixes/fixAddVoidToPromise.ts var fixName7 = "addVoidToPromise"; -var fixId52 = "addVoidToPromise"; -var errorCodes65 = [ +var fixId53 = "addVoidToPromise"; +var errorCodes66 = [ Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code ]; registerCodeFix({ - errorCodes: errorCodes65, - fixIds: [fixId52], + errorCodes: errorCodes66, + fixIds: [fixId53], getCodeActions(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange12(t, context.sourceFile, context.span, context.program)); if (changes.length > 0) { - return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId52, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)]; + return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId53, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)]; } }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes65, (changes, diag2) => makeChange12(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); + return codeFixAll(context, errorCodes66, (changes, diag2) => makeChange12(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); } }); function makeChange12(changes, sourceFile, span, program, seen) { const node = getTokenAtPosition(sourceFile, span.start); - if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) - return; + if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) return; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(node); const decl = symbol == null ? void 0 : symbol.valueDeclaration; - if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent)) - return; - if (seen == null ? void 0 : seen.has(decl)) - return; + if (!decl || !isParameter(decl) || !isNewExpression(decl.parent.parent)) return; + if (seen == null ? void 0 : seen.has(decl)) return; seen == null ? void 0 : seen.add(decl); const typeArguments = getEffectiveTypeArguments(decl.parent.parent); if (some(typeArguments)) { @@ -162417,8 +162629,7 @@ function completionEntryDataIsResolved(data) { } function continuePreviousIncompleteResponse(cache, file, location, program, host, preferences, cancellationToken, position) { const previousResponse = cache.get(); - if (!previousResponse) - return void 0; + if (!previousResponse) return void 0; const touchNode = getTouchingPropertyName(file, position); const lowerCaseTokenText = location.text.toLowerCase(); const exportMap = getExportInfoMap(file, host, program, preferences, cancellationToken); @@ -162444,8 +162655,7 @@ function continuePreviousIncompleteResponse(cache, file, location, program, host const { origin } = Debug.checkDefined(getAutoImportSymbolFromCompletionEntryData(entry.name, entry.data, program, host)); const info = exportMap.get(file.path, entry.data.exportMapKey); const result = info && context.tryResolve(info, !isExternalModuleNameRelative(stripQuotes(origin.moduleSymbol.name))); - if (result === "skipped") - return entry; + if (result === "skipped") return entry; if (!result || result === "failed") { (_a = host.log) == null ? void 0 : _a.call(host, `Unexpected failure resolving auto import for '${entry.name}' from '${entry.source}'`); return void 0; @@ -162526,8 +162736,7 @@ function getJSDocParameterCompletions(sourceFile, position, checker, options, pr ) : void 0; if (tagNameOnly) { displayText = displayText.slice(1); - if (snippetText) - snippetText = snippetText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); } return { name: displayText, @@ -162566,8 +162775,7 @@ function getJSDocParameterCompletions(sourceFile, position, checker, options, pr let snippetText = snippetTextResult == null ? void 0 : snippetTextResult.join(getNewLineCharacter(options) + "* "); if (tagNameOnly) { displayText = displayText.slice(1); - if (snippetText) - snippetText = snippetText.slice(1); + if (snippetText) snippetText = snippetText.slice(1); } return { name: displayText, @@ -162853,6 +163061,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, entries, keywordEntry, compareCompletionEntries, + /*equalityComparer*/ + void 0, /*allowDuplicates*/ true ); @@ -162866,6 +163076,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, entries, keywordEntry, compareCompletionEntries, + /*equalityComparer*/ + void 0, /*allowDuplicates*/ true ); @@ -162878,6 +163090,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, entries, literalEntry, compareCompletionEntries, + /*equalityComparer*/ + void 0, /*allowDuplicates*/ true ); @@ -163122,16 +163336,14 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, replacementSpan = createTextSpanFromBounds(dot.getStart(sourceFile), end); } if (isJsxInitializer) { - if (insertText === void 0) - insertText = name; + if (insertText === void 0) insertText = name; insertText = `{${insertText}}`; if (typeof isJsxInitializer !== "boolean") { replacementSpan = createTextSpanFromNode(isJsxInitializer, sourceFile); } } if (origin && originIsPromise(origin) && propertyAccessToConvert) { - if (insertText === void 0) - insertText = name; + if (insertText === void 0) insertText = name; const precedingToken = findPrecedingToken(propertyAccessToConvert.pos, sourceFile); let awaitText = ""; if (precedingToken && positionIsASICandidate(precedingToken.end, precedingToken.parent, sourceFile)) { @@ -163800,6 +164012,8 @@ function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, con entries, entry, compareCompletionEntries, + /*equalityComparer*/ + void 0, /*allowDuplicates*/ true ); @@ -163918,8 +164132,7 @@ function getSymbolCompletionFromEntryId(program, log, sourceFile, position, entr } const { symbols, literals, location, completionKind, symbolToOriginInfoMap, contextToken, previousToken, isJsxInitializer, isTypeOnlyLocation } = completionData; const literal = find(literals, (l) => completionNameForLiteral(sourceFile, preferences, l) === entryId.name); - if (literal !== void 0) - return { type: "literal", literal }; + if (literal !== void 0) return { type: "literal", literal }; return firstDefined(symbols, (symbol, index) => { const origin = symbolToOriginInfoMap[index]; const info = getCompletionEntryDisplayNameForSymbol(symbol, getEmitScriptTarget(compilerOptions), origin, completionKind, completionData.isJsxIdentifierExpected); @@ -164164,8 +164377,7 @@ function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { /*useOnlyExternalAliasing*/ false ); - if (chain) - return first(chain); + if (chain) return first(chain); return symbol.parent && (isModuleSymbol(symbol.parent) ? symbol : getFirstSymbolInChain(symbol.parent, enclosingDeclaration, checker)); } function isModuleSymbol(symbol) { @@ -164452,8 +164664,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node); if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) { const isNamespaceName = isModuleDeclaration(node.parent); - if (isNamespaceName) - isNewIdentifierLocation = true; + if (isNamespaceName) isNewIdentifierLocation = true; let symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = skipAlias(symbol, typeChecker); @@ -164638,8 +164849,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return result === 1 /* Success */; } function tryGetConstructorCompletion() { - if (!tryGetConstructorLikeCompletionContainer(contextToken)) - return 0 /* Continue */; + if (!tryGetConstructorLikeCompletionContainer(contextToken)) return 0 /* Continue */; completionKind = 5 /* None */; isNewIdentifierLocation = true; keywordFilters = 4 /* ConstructorParameterKeywords */; @@ -164648,8 +164858,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, function tryGetJsxCompletionSymbols() { const jsxContainer = tryGetContainingJsxElement(contextToken); const attrsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes); - if (!attrsType) - return 0 /* Continue */; + if (!attrsType) return 0 /* Continue */; const completionsType = jsxContainer && typeChecker.getContextualType(jsxContainer.attributes, 4 /* Completions */); symbols = concatenate(symbols, filterJsxAttributes(getPropertiesForObjectExpression(attrsType, completionsType, jsxContainer.attributes, typeChecker), jsxContainer.attributes.properties)); setSortTextToOptionalMember(); @@ -164658,8 +164867,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return 1 /* Success */; } function tryGetImportCompletionSymbols() { - if (!importStatementCompletion) - return 0 /* Continue */; + if (!importStatementCompletion) return 0 /* Continue */; isNewIdentifierLocation = true; collectAutoImports(); return 1 /* Success */; @@ -164713,14 +164921,10 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } function shouldOfferImportCompletions() { var _a; - if (importStatementCompletion) - return true; - if (!preferences.includeCompletionsForModuleExports) - return false; - if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) - return true; - if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) - return true; + if (importStatementCompletion) return true; + if (!preferences.includeCompletionsForModuleExports) return false; + if (sourceFile.externalModuleIndicator || sourceFile.commonJsModuleIndicator) return true; + if (compilerOptionsIndicateEsModules(program.getCompilerOptions())) return true; return ((_a = program.getSymlinkCache) == null ? void 0 : _a.call(program).hasAnySymlinks()) || !!program.getCompilerOptions().paths || programContainsModules(program); } function isSnippetScope(scopeNode) { @@ -164762,8 +164966,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } function collectAutoImports() { var _a, _b; - if (!shouldOfferImportCompletions()) - return; + if (!shouldOfferImportCompletions()) return; Debug.assert(!(detailsEntryId == null ? void 0 : detailsEntryId.data), "Should not run 'collectAutoImports' when faster path is available via `data`"); if (detailsEntryId && !detailsEntryId.source) { return; @@ -164790,19 +164993,13 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, /*preferCapitalized*/ isRightOfOpenTag, (symbolName2, targetFlags) => { - if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) - return false; - if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) - return false; - if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */)) - return false; - if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */))) - return false; + if (!isIdentifierText(symbolName2, getEmitScriptTarget(host.getCompilationSettings()))) return false; + if (!detailsEntryId && isStringANonContextualKeyword(symbolName2)) return false; + if (!isTypeOnlyLocation && !importStatementCompletion && !(targetFlags & 111551 /* Value */)) return false; + if (isTypeOnlyLocation && !(targetFlags & (1536 /* Module */ | 788968 /* Type */))) return false; const firstChar = symbolName2.charCodeAt(0); - if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */)) - return false; - if (detailsEntryId) - return true; + if (isRightOfOpenTag && (firstChar < 65 /* A */ || firstChar > 90 /* Z */)) return false; + if (detailsEntryId) return true; return charactersFuzzyMatchInString(symbolName2, lowerCaseTokenText); }, (info, symbolName2, isFromAmbientModule, exportMapKey) => { @@ -164814,8 +165011,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return; } const result = context.tryResolve(info, isFromAmbientModule) || {}; - if (result === "failed") - return; + if (result === "failed") return; let exportInfo2 = info[0], moduleSpecifier; if (result !== "skipped") { ({ exportInfo: exportInfo2 = info[0], moduleSpecifier } = result); @@ -164986,13 +165182,11 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } function tryGetObjectTypeLiteralInTypeArgumentCompletionSymbols() { const typeLiteralNode = tryGetTypeLiteralNode(contextToken); - if (!typeLiteralNode) - return 0 /* Continue */; + if (!typeLiteralNode) return 0 /* Continue */; const intersectionTypeNode = isIntersectionTypeNode(typeLiteralNode.parent) ? typeLiteralNode.parent : void 0; const containerTypeNode = intersectionTypeNode || typeLiteralNode; const containerExpectedType = getConstraintOfTypeArgumentProperty(containerTypeNode, typeChecker); - if (!containerExpectedType) - return 0 /* Continue */; + if (!containerExpectedType) return 0 /* Continue */; const containerActualType = typeChecker.getTypeFromTypeNode(containerTypeNode); const members = getPropertiesForCompletion(containerExpectedType, typeChecker); const existingMembers = getPropertiesForCompletion(containerActualType, typeChecker); @@ -165004,12 +165198,10 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return 1 /* Success */; } function tryGetObjectLikeCompletionSymbols() { - if ((contextToken == null ? void 0 : contextToken.kind) === 26 /* DotDotDotToken */) - return 0 /* Continue */; + if ((contextToken == null ? void 0 : contextToken.kind) === 26 /* DotDotDotToken */) return 0 /* Continue */; const symbolsStartIndex = symbols.length; const objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile); - if (!objectLikeContainer) - return 0 /* Continue */; + if (!objectLikeContainer) return 0 /* Continue */; completionKind = 0 /* ObjectPropertyDeclaration */; let typeMembers; let existingMembers; @@ -165036,8 +165228,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, Debug.assert(objectLikeContainer.kind === 206 /* ObjectBindingPattern */); isNewIdentifierLocation = false; const rootDeclaration = getRootDeclaration(objectLikeContainer.parent); - if (!isVariableLike(rootDeclaration)) - return Debug.fail("Root declaration is not variable-like."); + if (!isVariableLike(rootDeclaration)) return Debug.fail("Root declaration is not variable-like."); let canGetType = hasInitializer(rootDeclaration) || !!getEffectiveTypeAnnotationNode(rootDeclaration) || rootDeclaration.parent.parent.kind === 250 /* ForOfStatement */; if (!canGetType && rootDeclaration.kind === 169 /* Parameter */) { if (isExpression(rootDeclaration.parent)) { @@ -165048,8 +165239,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } if (canGetType) { const typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer); - if (!typeForObject) - return 2 /* Fail */; + if (!typeForObject) return 2 /* Fail */; typeMembers = typeChecker.getPropertiesOfType(typeForObject).filter((propertySymbol) => { return typeChecker.isPropertyAccessible( objectLikeContainer, @@ -165076,11 +165266,9 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return 1 /* Success */; } function tryGetImportOrExportClauseCompletionSymbols() { - if (!contextToken) - return 0 /* Continue */; + if (!contextToken) return 0 /* Continue */; const namedImportsOrExports = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isNamedImportsOrExports) : isTypeKeywordTokenOrIdentifier(contextToken) ? tryCast(contextToken.parent.parent, isNamedImportsOrExports) : void 0; - if (!namedImportsOrExports) - return 0 /* Continue */; + if (!namedImportsOrExports) return 0 /* Continue */; if (!isTypeKeywordTokenOrIdentifier(contextToken)) { keywordFilters = 8 /* TypeKeyword */; } @@ -165106,11 +165294,9 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return 1 /* Success */; } function tryGetImportAttributesCompletionSymbols() { - if (contextToken === void 0) - return 0 /* Continue */; + if (contextToken === void 0) return 0 /* Continue */; const importAttributes = contextToken.kind === 19 /* OpenBraceToken */ || contextToken.kind === 28 /* CommaToken */ ? tryCast(contextToken.parent, isImportAttributes) : contextToken.kind === 59 /* ColonToken */ ? tryCast(contextToken.parent.parent, isImportAttributes) : void 0; - if (importAttributes === void 0) - return 0 /* Continue */; + if (importAttributes === void 0) return 0 /* Continue */; const existing = new Set(importAttributes.elements.map(getNameFromImportAttribute)); symbols = filter(typeChecker.getTypeAtLocation(importAttributes).getApparentProperties(), (attr) => !existing.has(attr.escapedName)); return 1 /* Success */; @@ -165135,13 +165321,11 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } function tryGetClassLikeCompletionSymbols() { const decl = tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken, location, position); - if (!decl) - return 0 /* Continue */; + if (!decl) return 0 /* Continue */; completionKind = 3 /* MemberLike */; isNewIdentifierLocation = true; keywordFilters = contextToken.kind === 42 /* AsteriskToken */ ? 0 /* None */ : isClassLike(decl) ? 2 /* ClassElementKeywords */ : 3 /* InterfaceElementKeywords */; - if (!isClassLike(decl)) - return 1 /* Success */; + if (!isClassLike(decl)) return 1 /* Success */; const classElement = contextToken.kind === 27 /* SemicolonToken */ ? contextToken.parent.parent : contextToken.parent; let classElementModifierFlags = isClassElement(classElement) ? getEffectiveModifierFlags(classElement) : 0 /* None */; if (contextToken.kind === 80 /* Identifier */ && !isCurrentlyEditingNode(contextToken)) { @@ -165234,8 +165418,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, /*startNode*/ void 0 ); - if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */) - break; + if (!parent2.typeArguments || precedingToken && precedingToken.kind === 44 /* SlashToken */) break; } return parent2; } else if (parent2.kind === 291 /* JsxAttribute */) { @@ -165574,11 +165757,9 @@ function getAutoImportSymbolFromCompletionEntryData(name, data, program, host) { const containingProgram = data.isPackageJsonImport ? host.getPackageJsonAutoImportProvider() : program; const checker = containingProgram.getTypeChecker(); const moduleSymbol = data.ambientModuleName ? checker.tryFindAmbientModule(data.ambientModuleName) : data.fileName ? checker.getMergedSymbol(Debug.checkDefined(containingProgram.getSourceFile(data.fileName)).symbol) : void 0; - if (!moduleSymbol) - return void 0; + if (!moduleSymbol) return void 0; let symbol = data.exportName === "export=" /* ExportEquals */ ? checker.resolveExternalModuleSymbol(moduleSymbol) : checker.tryGetMemberInModuleExportsAndProperties(data.exportName, moduleSymbol); - if (!symbol) - return void 0; + if (!symbol) return void 0; const isDefaultExport = data.exportName === "default" /* Default */; symbol = isDefaultExport && getLocalSymbolForExportDefault(symbol) || symbol; return { symbol, origin: completionEntryDataToSymbolOriginInfo(data, name, moduleSymbol) }; @@ -165624,8 +165805,7 @@ var allKeywordsCompletions = memoize(() => { return res; }); function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { - if (!filterOutTsOnlyKeywords) - return getTypescriptKeywordCompletions(keywordFilter); + if (!filterOutTsOnlyKeywords) return getTypescriptKeywordCompletions(keywordFilter); const index = keywordFilter + 8 /* Last */ + 1; return _keywordCompletions[index] || (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter).filter((entry) => !isTypeScriptOnlyKeyword(stringToToken(entry.name)))); } @@ -165741,14 +165921,12 @@ function getPropertiesForObjectExpression(contextualType, completionsType, obj, const properties = getApparentProperties(type, obj, checker); return type.isClass() && containsNonPublicProperties(properties) ? [] : hasCompletionsType ? filter(properties, hasDeclarationOtherThanSelf) : properties; function hasDeclarationOtherThanSelf(member) { - if (!length(member.declarations)) - return true; + if (!length(member.declarations)) return true; return some(member.declarations, (decl) => decl.parent !== obj); } } function getApparentProperties(type, node, checker) { - if (!type.isUnion()) - return type.getApparentProperties(); + if (!type.isUnion()) return type.getApparentProperties(); return checker.getAllPossiblePropertiesOfTypes(filter(type.types, (memberType) => !(memberType.flags & 402784252 /* Primitive */ || checker.isArrayLikeType(memberType) || checker.isTypeInvalidDueToUnionDiscriminant(memberType, node) || checker.typeHasCallOrConstructSignatures(memberType) || memberType.isClass() && containsNonPublicProperties(memberType.getApparentProperties())))); } function containsNonPublicProperties(props) { @@ -165785,8 +165963,7 @@ function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken } } } - if (!contextToken) - return void 0; + if (!contextToken) return void 0; if (location.kind === 137 /* ConstructorKeyword */ || isIdentifier(contextToken) && isPropertyDeclaration(contextToken.parent) && isClassLike(location)) { return findAncestor(contextToken, isClassLike); } @@ -165811,8 +165988,7 @@ function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken } } function tryGetTypeLiteralNode(node) { - if (!node) - return void 0; + if (!node) return void 0; const parent2 = node.parent; switch (node.kind) { case 19 /* OpenBraceToken */: @@ -165831,14 +166007,12 @@ function tryGetTypeLiteralNode(node) { return void 0; } function getConstraintOfTypeArgumentProperty(node, checker) { - if (!node) - return void 0; + if (!node) return void 0; if (isTypeNode(node) && isTypeReferenceType(node.parent)) { return checker.getTypeArgumentConstraint(node); } const t = getConstraintOfTypeArgumentProperty(node.parent, checker); - if (!t) - return void 0; + if (!t) return void 0; switch (node.kind) { case 171 /* PropertySignature */: return checker.getTypeOfPropertyOfContextualType(t, node.symbol.escapedName); @@ -165988,8 +166162,7 @@ function getImportStatementCompletionInfo(contextToken, sourceFile) { } function getSingleLineReplacementSpanForImportCompletionNode(node) { var _a; - if (!node) - return void 0; + if (!node) return void 0; const top = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration, isJSDocImportTag)) ?? node; const sourceFile = top.getSourceFile(); if (rangeIsOnSingleLine(top, sourceFile)) { @@ -166031,13 +166204,11 @@ function canCompleteFromNamedBindings(namedBindings) { } function isModuleSpecifierMissingOrEmpty(specifier) { var _a; - if (nodeIsMissing(specifier)) - return true; + if (nodeIsMissing(specifier)) return true; return !((_a = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a.text); } function getVariableOrParameterDeclaration(contextToken, location) { - if (!contextToken) - return; + if (!contextToken) return; const possiblyParameterDeclaration = findAncestor(contextToken, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent)); const possiblyVariableDeclaration = findAncestor(location, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); return possiblyParameterDeclaration || possiblyVariableDeclaration; @@ -166125,8 +166296,7 @@ function getStringLiteralCompletions(sourceFile, position, contextToken, options return entries && convertPathCompletions(entries); } if (isInString(sourceFile, position, contextToken)) { - if (!contextToken || !isStringLiteralLike(contextToken)) - return void 0; + if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; const entries = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences); return convertStringLiteralCompletions(entries, contextToken, sourceFile, host, program, log, options, preferences, position, includeSymbol); } @@ -166198,8 +166368,7 @@ function convertStringLiteralCompletions(completion, contextToken, sourceFile, h } } function getStringLiteralCompletionDetails(name, sourceFile, position, contextToken, program, host, cancellationToken, preferences) { - if (!contextToken || !isStringLiteralLike(contextToken)) - return void 0; + if (!contextToken || !isStringLiteralLike(contextToken)) return void 0; const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, program, host, preferences); return completions && stringLiteralCompletionDetails(name, contextToken, completions, sourceFile, program.getTypeChecker(), cancellationToken); } @@ -166363,8 +166532,7 @@ function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, check const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg; const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument); const types = flatMap(candidates, (candidate) => { - if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) - return; + if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; let type = candidate.getTypeParameterAtPosition(argumentInfo.argumentIndex); if (isJsxOpeningLikeElement(call)) { const propType = checker.getTypeOfPropertyOfType(type, getTextOfJsxAttributeName(editingArgument.name)); @@ -166386,8 +166554,7 @@ function stringLiteralCompletionsFromProperties(type) { } function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpression) { const contextualType = checker.getContextualType(objectLiteralExpression); - if (!contextualType) - return void 0; + if (!contextualType) return void 0; const completionsType = checker.getContextualType(objectLiteralExpression, 4 /* Completions */); const symbols = getPropertiesForObjectExpression( contextualType, @@ -166402,8 +166569,7 @@ function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpressi }; } function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) { - if (!type) - return emptyArray; + if (!type) return emptyArray; type = skipConstraint(type); return type.isUnion() ? flatMap(type.types, (t) => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray; } @@ -166473,8 +166639,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, p function getSupportedExtensionsForModuleResolution(compilerOptions, typeChecker) { const ambientModulesExtensions = !typeChecker ? [] : mapDefined(typeChecker.getAmbientModules(), (module2) => { const name = module2.name.slice(1, -1); - if (!name.startsWith("*.") || name.includes("/")) - return; + if (!name.startsWith("*.") || name.includes("/")) return; return name.slice(1); }); const extensions = [...getSupportedExtensions(compilerOptions), ambientModulesExtensions]; @@ -166542,8 +166707,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext } } const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); - if (!tryDirectoryExists(host, baseDirectory)) - return result; + if (!tryDirectoryExists(host, baseDirectory)) return result; const files = tryReadDirectory( host, baseDirectory, @@ -166637,14 +166801,12 @@ function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, bas let pathResults = []; let matchedPath; for (const key of keys) { - if (key === ".") - continue; + if (key === ".") continue; const keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); const patterns = getPatternsForKey(key); if (patterns) { const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash); - if (!pathPattern) - continue; + if (!pathPattern) continue; const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment); const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(key, matchedPath) === -1 /* LessThan */); if (isLongestMatch) { @@ -166918,12 +167080,10 @@ function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDire } return result; function getCompletionEntriesFromDirectories(directory) { - if (!tryDirectoryExists(host, directory)) - return; + if (!tryDirectoryExists(host, directory)) return; for (const typeDirectoryName of tryGetDirectories(host, directory)) { const packageName = unmangleScopedPackageName(typeDirectoryName); - if (options.types && !contains(options.types, packageName)) - continue; + if (options.types && !contains(options.types, packageName)) continue; if (fragmentDirectory === void 0) { if (!seen.has(packageName)) { result.add(nameAndKind( @@ -166956,15 +167116,13 @@ function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDire } } function enumerateNodeModulesVisibleToScript(host, scriptPath) { - if (!host.readFile || !host.fileExists) - return emptyArray; + if (!host.readFile || !host.fileExists) return emptyArray; const result = []; for (const packageJson of findPackageJsons(scriptPath, host)) { const contents = readJson(packageJson, host); for (const key of nodeModulesDependencyKeys) { const dependencies = contents[key]; - if (!dependencies) - continue; + if (!dependencies) continue; for (const dep in dependencies) { if (hasProperty(dependencies, dep) && !startsWith(dep, "@types/")) { result.push(dep); @@ -167073,8 +167231,7 @@ function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { if (!markSeenDirectImport(direct)) { continue; } - if (cancellationToken) - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) cancellationToken.throwIfCancellationRequested(); switch (direct.kind) { case 213 /* CallExpression */: if (isImportCall(direct)) { @@ -167163,15 +167320,13 @@ function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { } function isExported2(node, stopAtAmbientModule = false) { return findAncestor(node, (node2) => { - if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) - return "quit"; + if (stopAtAmbientModule && isAmbientModuleDeclaration(node2)) return "quit"; return canHaveModifiers(node2) && some(node2.modifiers, isExportModifier); }); } function handleNamespaceImport(importDeclaration, name, isReExport, alreadyAddedDirect) { if (exportKind === 2 /* ExportEquals */) { - if (!alreadyAddedDirect) - directImports.push(importDeclaration); + if (!alreadyAddedDirect) directImports.push(importDeclaration); } else if (!isAvailableThroughGlobal) { const sourceFileLike = getSourceFileLikeForImportDeclaration(importDeclaration); Debug.assert(sourceFileLike.kind === 307 /* SourceFile */ || sourceFileLike.kind === 267 /* ModuleDeclaration */); @@ -167189,14 +167344,11 @@ function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { function addIndirectUser(sourceFileLike, addTransitiveDependencies = false) { Debug.assert(!isAvailableThroughGlobal); const isNew = markSeenIndirectUser(sourceFileLike); - if (!isNew) - return; + if (!isNew) return; indirectUserDeclarations.push(sourceFileLike); - if (!addTransitiveDependencies) - return; + if (!addTransitiveDependencies) return; const moduleSymbol = checker.getMergedSymbol(sourceFileLike.symbol); - if (!moduleSymbol) - return; + if (!moduleSymbol) return; Debug.assert(!!(moduleSymbol.flags & 1536 /* Module */)); const directImports2 = getDirectImports(moduleSymbol); if (directImports2) { @@ -167310,8 +167462,7 @@ function getSearchesFromDirectImports(directImports, exportSymbol, exportKind, c function findNamespaceReExports(sourceFileLike, name, checker) { const namespaceImportSymbol = checker.getSymbolAtLocation(name); return !!forEachPossibleImportOrExportStatement(sourceFileLike, (statement) => { - if (!isExportDeclaration(statement)) - return; + if (!isExportDeclaration(statement)) return; const { exportClause, moduleSpecifier } = statement; return !moduleSpecifier && exportClause && isNamedExports(exportClause) && exportClause.elements.some((element) => checker.getExportSpecifierLocalTargetSymbol(element) === namespaceImportSymbol); }); @@ -167329,7 +167480,7 @@ function findModuleReferences(program, sourceFiles, searchModuleSymbol) { } } for (const ref of referencingFile.typeReferenceDirectives) { - const referenced = (_a = program.getResolvedTypeReferenceDirectives().get(ref.fileName, ref.resolutionMode || program.getDefaultResolutionModeForFile(referencingFile))) == null ? void 0 : _a.resolvedTypeReferenceDirective; + const referenced = (_a = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(ref, referencingFile)) == null ? void 0 : _a.resolvedTypeReferenceDirective; if (referenced !== void 0 && referenced.resolvedFileName === searchSourceFile.fileName) { refs.push({ kind: "reference", referencingFile, ref }); } @@ -167347,8 +167498,7 @@ function findModuleReferences(program, sourceFiles, searchModuleSymbol) { function getDirectImportsMap(sourceFiles, checker, cancellationToken) { const map2 = /* @__PURE__ */ new Map(); for (const sourceFile of sourceFiles) { - if (cancellationToken) - cancellationToken.throwIfCancellationRequested(); + if (cancellationToken) cancellationToken.throwIfCancellationRequested(); forEachImport(sourceFile, (importDecl, moduleSpecifier) => { const moduleSymbol = checker.getSymbolAtLocation(moduleSpecifier); if (moduleSymbol) { @@ -167447,8 +167597,7 @@ function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { } } function getExportAssignmentExport(ex) { - if (!ex.symbol.parent) - return void 0; + if (!ex.symbol.parent) return void 0; const exportKind = ex.isExportEquals ? 2 /* ExportEquals */ : 1 /* Default */; return { kind: 1 /* Export */, symbol, exportInfo: { exportingModuleSymbol: ex.symbol.parent, exportKind } }; } @@ -167470,16 +167619,13 @@ function getImportOrExportSymbol(node, symbol, checker, comingFromExport) { } function getImport() { const isImport3 = isNodeImport(node); - if (!isImport3) - return void 0; + if (!isImport3) return void 0; let importedSymbol = checker.getImmediateAliasedSymbol(symbol); - if (!importedSymbol) - return void 0; + if (!importedSymbol) return void 0; importedSymbol = skipExportSpecifierSymbol(importedSymbol, checker); if (importedSymbol.escapedName === "export=") { importedSymbol = getExportEqualsLocalSymbol(importedSymbol, checker); - if (importedSymbol === void 0) - return void 0; + if (importedSymbol === void 0) return void 0; } const importedName = symbolEscapedNameNoDefault(importedSymbol); if (importedName === void 0 || importedName === "default" /* Default */ || importedName === symbol.escapedName) { @@ -167536,8 +167682,7 @@ function isNodeImport(node) { } function getExportInfo(exportSymbol, exportKind, checker) { const moduleSymbol = exportSymbol.parent; - if (!moduleSymbol) - return void 0; + if (!moduleSymbol) return void 0; const exportingModuleSymbol = checker.getMergedSymbol(moduleSymbol); return isExternalModuleSymbol(exportingModuleSymbol) ? { exportingModuleSymbol, exportKind } : void 0; } @@ -167608,8 +167753,7 @@ function getContextNodeForNodeEntry(node) { if (isDeclaration(node)) { return getContextNode(node); } - if (!node.parent) - return void 0; + if (!node.parent) return void 0; if (!isDeclaration(node.parent) && !isExportAssignment(node.parent)) { if (isInJSFile(node)) { const binaryExpression = isBinaryExpression(node.parent) ? node.parent : isAccessExpression(node.parent) && isBinaryExpression(node.parent.parent) && node.parent.parent.left === node.parent ? node.parent.parent : void 0; @@ -167640,8 +167784,7 @@ function getContextNodeForNodeEntry(node) { return void 0; } function getContextNode(node) { - if (!node) - return void 0; + if (!node) return void 0; switch (node.kind) { case 260 /* VariableDeclaration */: return !isVariableDeclarationList(node.parent) || node.parent.declarations.length !== 1 ? node : isVariableStatement(node.parent.parent) ? node.parent.parent : isForInOrOfStatement(node.parent.parent) ? getContextNode(node.parent.parent) : node.parent; @@ -167678,8 +167821,7 @@ function getContextNode(node) { } } function toContextSpan(textSpan, sourceFile, context) { - if (!context) - return void 0; + if (!context) return void 0; const contextSpan = isContextWithStartAndEndNode(context) ? getTextSpan(context.start, sourceFile, context.end) : getTextSpan(context, sourceFile); return contextSpan.start !== textSpan.start || contextSpan.length !== textSpan.length ? { contextSpan } : void 0; } @@ -167846,8 +167988,7 @@ function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTe } function toReferencedSymbolEntry(entry, symbol) { const referenceEntry = toReferenceEntry(entry); - if (!symbol) - return referenceEntry; + if (!symbol) return referenceEntry; return { ...referenceEntry, isDefinition: entry.kind !== 0 /* Span */ && isDeclarationOfSymbol(entry.node, symbol) @@ -167879,7 +168020,7 @@ function entryToDocumentSpan(entry) { } } function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { - if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { + if (entry.kind !== 0 /* Span */ && (isIdentifier(originalNode) || isStringLiteralLike(originalNode))) { const { node, kind } = entry; const parent2 = node.parent; const name = originalNode.text; @@ -167987,15 +168128,13 @@ function isWriteAccessForReference(node) { } function isDeclarationOfSymbol(node, target) { var _a; - if (!target) - return false; + if (!target) return false; const source = getDeclarationFromName(node) || (node.kind === 90 /* DefaultKeyword */ ? node.parent : isLiteralComputedPropertyDeclarationName(node) ? node.parent.parent : node.kind === 137 /* ConstructorKeyword */ && isConstructorDeclaration(node.parent) ? node.parent.parent : void 0); const commonjsSource = source && isBinaryExpression(source) ? source.left : void 0; return !!(source && ((_a = target.declarations) == null ? void 0 : _a.some((d) => d === source || d === commonjsSource))); } function declarationIsWriteAccess(decl) { - if (!!(decl.flags & 33554432 /* Ambient */)) - return true; + if (!!(decl.flags & 33554432 /* Ambient */)) return true; switch (decl.kind) { case 226 /* BinaryExpression */: case 208 /* BindingElement */: @@ -168171,12 +168310,10 @@ var Core; } function getReferencedSymbolsForModuleIfDeclaredBySourceFile(symbol, program, sourceFiles, cancellationToken, options, sourceFilesSet) { const moduleSourceFile = symbol.flags & 1536 /* Module */ && symbol.declarations && find(symbol.declarations, isSourceFile); - if (!moduleSourceFile) - return void 0; + if (!moduleSourceFile) return void 0; const exportEquals = symbol.exports.get("export=" /* ExportEquals */); const moduleReferences = getReferencedSymbolsForModule(program, symbol, !!exportEquals, sourceFiles, sourceFilesSet); - if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) - return moduleReferences; + if (!exportEquals || !sourceFilesSet.has(moduleSourceFile.fileName)) return moduleReferences; const checker = program.getTypeChecker(); symbol = skipAlias(exportEquals, checker); return mergeReferences(program, moduleReferences, getReferencedSymbolsForSymbol( @@ -168193,8 +168330,7 @@ var Core; function mergeReferences(program, ...referencesToMerge) { let result; for (const references of referencesToMerge) { - if (!references || !references.length) - continue; + if (!references || !references.length) continue; if (!result) { result = references; continue; @@ -168406,8 +168542,7 @@ var Core; } return firstDefined(symbol.declarations, (decl) => { if (!decl.parent) { - if (symbol.flags & 33554432 /* Transient */) - return void 0; + if (symbol.flags & 33554432 /* Transient */) return void 0; Debug.fail(`Unexpected symbol at ${Debug.formatSyntaxKind(node.kind)}: ${Debug.formatSymbol(symbol)}`); } return isTypeLiteralNode(decl.parent) && isUnionTypeNode(decl.parent.parent) ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) : void 0; @@ -168420,8 +168555,7 @@ var Core; SpecialSearchKind2[SpecialSearchKind2["Class"] = 2] = "Class"; })(SpecialSearchKind || (SpecialSearchKind = {})); function getNonModuleSymbolOfMergedModuleSymbol(symbol) { - if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */))) - return void 0; + if (!(symbol.flags & (1536 /* Module */ | 33554432 /* Transient */))) return void 0; const decl = symbol.declarations && find(symbol.declarations, (d) => !isSourceFile(d) && !isModuleDeclaration(d)); return decl && decl.symbol; } @@ -168466,8 +168600,7 @@ var Core; } /** Gets every place to look for references of an exported symbols. See `ImportsResult` in `importTracker.ts` for more documentation. */ getImportSearches(exportSymbol, exportInfo) { - if (!this.importTracker) - this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); + if (!this.importTracker) this.importTracker = createImportTracker(this.sourceFiles, this.sourceFilesSet, this.checker, this.cancellationToken); return this.importTracker(exportSymbol, exportInfo, this.options.use === 2 /* Rename */); } /** @param allSearchSymbols set of additional symbols for use by `includes`. */ @@ -168516,8 +168649,7 @@ var Core; if (singleReferences.length) { const addRef = state.referenceAdder(exportSymbol); for (const singleRef of singleReferences) { - if (shouldAddSingleReference(singleRef, state)) - addRef(singleRef); + if (shouldAddSingleReference(singleRef, state)) addRef(singleRef); } } for (const [importLocation, importSymbol] of importSearches) { @@ -168570,17 +168702,13 @@ var Core; } Core2.eachExportReference = eachExportReference; function shouldAddSingleReference(singleRef, state) { - if (!hasMatchingMeaning(singleRef, state)) - return false; - if (state.options.use !== 2 /* Rename */) - return true; - if (!isIdentifier(singleRef)) - return false; + if (!hasMatchingMeaning(singleRef, state)) return false; + if (state.options.use !== 2 /* Rename */) return true; + if (!isIdentifier(singleRef)) return false; return !(isImportOrExportSpecifier(singleRef.parent) && singleRef.escapedText === "default" /* Default */); } function searchForImportedSymbol(symbol, state) { - if (!symbol.declarations) - return; + if (!symbol.declarations) return; for (const declaration of symbol.declarations) { const exportingFile = declaration.getSourceFile(); getReferencesInSourceFile(exportingFile, state.createSearch(declaration, symbol, 0 /* Import */), state, state.includesSourceFile(exportingFile)); @@ -168641,16 +168769,13 @@ var Core; Core2.isSymbolReferencedInFile = isSymbolReferencedInFile; function eachSymbolReferenceInFile(definition, checker, sourceFile, cb, searchContainer = sourceFile) { const symbol = isParameterPropertyDeclaration(definition.parent, definition.parent.parent) ? first(checker.getSymbolsOfParameterPropertyDeclaration(definition.parent, definition.text)) : checker.getSymbolAtLocation(definition); - if (!symbol) - return void 0; + if (!symbol) return void 0; for (const token of getPossibleSymbolReferenceNodes(sourceFile, symbol.name, searchContainer)) { - if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) - continue; + if (!isIdentifier(token) || token === definition || token.escapedText !== definition.escapedText) continue; const referenceSymbol = checker.getSymbolAtLocation(token); if (referenceSymbol === symbol || checker.getShorthandAssignmentValueSymbol(token.parent) === symbol || isExportSpecifier(token.parent) && getLocalSymbolForExportSpecifier(token, referenceSymbol, token.parent, checker) === symbol) { const res = cb(token); - if (res) - return res; + if (res) return res; } } } @@ -168679,13 +168804,11 @@ var Core; } Core2.getTopMostDeclarationNamesInFile = getTopMostDeclarationNamesInFile; function someSignatureUsage(signature, sourceFiles, checker, cb) { - if (!signature.name || !isIdentifier(signature.name)) - return false; + if (!signature.name || !isIdentifier(signature.name)) return false; const symbol = Debug.checkDefined(checker.getSymbolAtLocation(signature.name)); for (const sourceFile of sourceFiles) { for (const name of getPossibleSymbolReferenceNodes(sourceFile, symbol.name)) { - if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) - continue; + if (!isIdentifier(name) || name === signature.name || name.escapedText !== signature.name.escapedText) continue; const called = climbPastPropertyAccess(name); const call = isCallExpression(called.parent) && called.parent.expression === called ? called.parent : void 0; const referenceSymbol = checker.getSymbolAtLocation(name); @@ -168715,8 +168838,7 @@ var Core; const symbolNameLength = symbolName2.length; let position = text.indexOf(symbolName2, container.pos); while (position >= 0) { - if (position > container.end) - break; + if (position > container.end) break; const endPosition = position + symbolNameLength; if ((position === 0 || !isIdentifierPart(text.charCodeAt(position - 1), 99 /* Latest */)) && (endPosition === sourceLength || !isIdentifierPart(text.charCodeAt(endPosition), 99 /* Latest */))) { positions.push(position); @@ -168801,8 +168923,7 @@ var Core; } return; } - if (!hasMatchingMeaning(referenceLocation, state)) - return; + if (!hasMatchingMeaning(referenceLocation, state)) return; let referenceSymbol = state.checker.getSymbolAtLocation(referenceLocation); if (!referenceSymbol) { return; @@ -168827,8 +168948,7 @@ var Core; } switch (state.specialSearchKind) { case 0 /* None */: - if (addReferencesHere) - addReference(referenceLocation, relatedSymbol, state); + if (addReferencesHere) addReference(referenceLocation, relatedSymbol, state); break; case 1 /* Constructor */: addConstructorReferences(referenceLocation, sourceFile, search, state); @@ -168841,8 +168961,7 @@ var Core; } if (isInJSFile(referenceLocation) && isBindingElement(referenceLocation.parent) && isVariableDeclarationInitializedToBareOrAccessedRequire(referenceLocation.parent.parent.parent)) { referenceSymbol = referenceLocation.parent.symbol; - if (!referenceSymbol) - return; + if (!referenceSymbol) return; } getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } @@ -168890,12 +169009,10 @@ var Core; } if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); - if (imported) - searchForImportedSymbol(imported, state); + if (imported) searchForImportedSymbol(imported, state); } function addRef() { - if (addReferencesHere) - addReference(referenceLocation, localSymbol, state); + if (addReferencesHere) addReference(referenceLocation, localSymbol, state); } } function getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, checker) { @@ -168912,8 +169029,7 @@ var Core; } function getImportOrExportReferences(referenceLocation, referenceSymbol, search, state) { const importOrExport = getImportOrExportSymbol(referenceLocation, referenceSymbol, state.checker, search.comingFrom === 1 /* Export */); - if (!importOrExport) - return; + if (!importOrExport) return; const { symbol } = importOrExport; if (importOrExport.kind === 0 /* Import */) { if (!isForRenameWithPrefixAndSuffixText(state.options)) { @@ -168961,8 +169077,7 @@ var Core; function addClassStaticThisReferences(referenceLocation, search, state) { addReference(referenceLocation, search.symbol, state); const classLike = referenceLocation.parent; - if (state.options.use === 2 /* Rename */ || !isClassLike(classLike)) - return; + if (state.options.use === 2 /* Rename */ || !isClassLike(classLike)) return; Debug.assert(classLike.name === referenceLocation); const addRef = state.referenceAdder(search.symbol); for (const member of classLike.members) { @@ -169029,8 +169144,7 @@ var Core; return !!getClassConstructorSymbol(classDeclaration.symbol); } function findInheritedConstructorReferences(classDeclaration, state) { - if (hasOwnConstructor(classDeclaration)) - return; + if (hasOwnConstructor(classDeclaration)) return; const classSymbol = classDeclaration.symbol; const search = state.createSearch( /*location*/ @@ -169066,8 +169180,7 @@ var Core; const body = typeHavingNode.body; if (body.kind === 241 /* Block */) { forEachReturnStatement(body, (returnStatement) => { - if (returnStatement.expression) - addIfImplementation(returnStatement.expression); + if (returnStatement.expression) addIfImplementation(returnStatement.expression); }); } else { addIfImplementation(body); @@ -169077,8 +169190,7 @@ var Core; } } function addIfImplementation(e) { - if (isImplementationExpression(e)) - addReference2(e); + if (isImplementationExpression(e)) addReference2(e); } } function getContainingNodeIfInHeritageClause(node) { @@ -169206,8 +169318,7 @@ var Core; /*includeClassComputedPropertyName*/ false ); - if (!canHaveSymbol(container)) - return false; + if (!canHaveSymbol(container)) return false; switch (searchSpaceNode.kind) { case 218 /* FunctionExpression */: case 262 /* FunctionDeclaration */: @@ -169304,8 +169415,7 @@ var Core; ), (sym) => fromRoot(sym, 4 /* SearchedPropertyFoundLocal */) ); - if (res2) - return res2; + if (res2) return res2; const propertySymbol = getPropertySymbolOfDestructuringAssignment(location, checker); const res1 = propertySymbol && cbSymbol( propertySymbol, @@ -169315,8 +169425,7 @@ var Core; void 0, 4 /* SearchedPropertyFoundLocal */ ); - if (res1) - return res1; + if (res1) return res1; const res22 = shorthandValueSymbol && cbSymbol( shorthandValueSymbol, /*rootSymbol*/ @@ -169325,8 +169434,7 @@ var Core; void 0, 3 /* SearchedLocalFoundProperty */ ); - if (res22) - return res22; + if (res22) return res22; } const aliasedSymbol = getMergedAliasedSymbolOfNamespaceExportDeclaration(location, symbol, checker); if (aliasedSymbol) { @@ -169338,12 +169446,10 @@ var Core; void 0, 1 /* Node */ ); - if (res2) - return res2; + if (res2) return res2; } const res = fromRoot(symbol); - if (res) - return res; + if (res) return res; if (symbol.valueDeclaration && isParameterPropertyDeclaration(symbol.valueDeclaration, symbol.valueDeclaration.parent)) { const paramProps = checker.getSymbolsOfParameterPropertyDeclaration(cast(symbol.valueDeclaration, isParameter), symbol.name); Debug.assert(paramProps.length === 2 && !!(paramProps[0].flags & 1 /* FunctionScopedVariable */) && !!(paramProps[1].flags & 4 /* Property */)); @@ -169361,8 +169467,7 @@ var Core; void 0, 1 /* Node */ ); - if (res2) - return res2; + if (res2) return res2; } } if (!isForRenamePopulateSearchSymbolSet) { @@ -169400,8 +169505,7 @@ var Core; const seen = /* @__PURE__ */ new Map(); return recur(symbol); function recur(symbol2) { - if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, getSymbolId(symbol2))) - return; + if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, getSymbolId(symbol2))) return; return firstDefined(symbol2.declarations, (declaration) => firstDefined(getAllSuperTypeNodes(declaration), (typeReference) => { const type = checker.getTypeAtLocation(typeReference); const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); @@ -169410,8 +169514,7 @@ var Core; } } function isStaticSymbol(symbol) { - if (!symbol.valueDeclaration) - return false; + if (!symbol.valueDeclaration) return false; const modifierFlags = getEffectiveModifierFlags(symbol.valueDeclaration); return !!(modifierFlags & 256 /* Static */); } @@ -169589,7 +169692,7 @@ function getDefinitionAtPosition(program, sourceFile, position, searchOtherFiles } } if (!symbol && isModuleSpecifierLike(fallbackNode)) { - const ref = (_a = program.getResolvedModuleFromModuleSpecifier(fallbackNode)) == null ? void 0 : _a.resolvedModule; + const ref = (_a = program.getResolvedModuleFromModuleSpecifier(fallbackNode, sourceFile)) == null ? void 0 : _a.resolvedModule; if (ref) { return [{ name: fallbackNode.text, @@ -169607,10 +169710,9 @@ function getDefinitionAtPosition(program, sourceFile, position, searchOtherFiles if (!symbol) { return concatenate(fileReferenceDefinition, getDefinitionInfoForIndexSignatures(node, typeChecker)); } - if (searchOtherFilesOnly && every(symbol.declarations, (d) => d.getSourceFile().fileName === sourceFile.fileName)) - return void 0; + if (searchOtherFilesOnly && every(symbol.declarations, (d) => d.getSourceFile().fileName === sourceFile.fileName)) return void 0; const calledDeclaration = tryGetSignatureDeclaration(typeChecker, node); - if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isConstructorLike(calledDeclaration))) { + if (calledDeclaration && !(isJsxOpeningLikeElement(node.parent) && isJsxConstructorLike(calledDeclaration))) { const sigInfo = createDefinitionFromSignatureDeclaration(typeChecker, calledDeclaration, failedAliasResolution); if (typeChecker.getRootSymbols(symbol).some((s) => symbolMatchesSignature(s, calledDeclaration))) { return [sigInfo]; @@ -169665,22 +169767,17 @@ function getDefinitionFromObjectLiteralElement(typeChecker, node) { } function getDefinitionFromOverriddenMember(typeChecker, node) { const classElement = findAncestor(node, isClassElement); - if (!(classElement && classElement.name)) - return; + if (!(classElement && classElement.name)) return; const baseDeclaration = findAncestor(classElement, isClassLike); - if (!baseDeclaration) - return; + if (!baseDeclaration) return; const baseTypeNode = getEffectiveBaseTypeNode(baseDeclaration); - if (!baseTypeNode) - return; + if (!baseTypeNode) return; const expression = skipParentheses(baseTypeNode.expression); const base = isClassExpression(expression) ? expression.symbol : typeChecker.getSymbolAtLocation(expression); - if (!base) - return; + if (!base) return; const name = unescapeLeadingUnderscores(getTextOfPropertyName(classElement.name)); const symbol = hasStaticModifier(classElement) ? typeChecker.getPropertyOfType(typeChecker.getTypeOfSymbol(base), name) : typeChecker.getPropertyOfType(typeChecker.getDeclaredTypeOfSymbol(base), name); - if (!symbol) - return; + if (!symbol) return; return getDefinitionFromSymbol(typeChecker, symbol, node); } function getReferenceAtPosition(sourceFile, position, program) { @@ -169692,7 +169789,7 @@ function getReferenceAtPosition(sourceFile, position, program) { } const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); if (typeReferenceDirective) { - const reference = (_a = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName, typeReferenceDirective.resolutionMode || program.getDefaultResolutionModeForFile(sourceFile))) == null ? void 0 : _a.resolvedTypeReferenceDirective; + const reference = (_a = program.getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeReferenceDirective, sourceFile)) == null ? void 0 : _a.resolvedTypeReferenceDirective; const file = reference && program.getSourceFile(reference.resolvedFileName); return file && { reference: typeReferenceDirective, fileName: file.fileName, file, unverified: false }; } @@ -169704,7 +169801,7 @@ function getReferenceAtPosition(sourceFile, position, program) { if (sourceFile.imports.length || sourceFile.moduleAugmentations.length) { const node = getTouchingToken(sourceFile, position); let resolution; - if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && (resolution = program.getResolvedModuleFromModuleSpecifier(node))) { + if (isModuleSpecifierLike(node) && isExternalModuleNameRelative(node.text) && (resolution = program.getResolvedModuleFromModuleSpecifier(node, sourceFile))) { const verifiedFileName = (_b = resolution.resolvedModule) == null ? void 0 : _b.resolvedFileName; const fileName = verifiedFileName || resolvePath(getDirectoryPath(sourceFile.fileName), node.text); return { @@ -169811,8 +169908,7 @@ function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { /*stopAtAlias*/ false ); - if (!symbol) - return void 0; + if (!symbol) return void 0; const typeAtLocation = typeChecker.getTypeOfSymbolAtLocation(symbol, node); const returnType = tryGetReturnTypeOfFunction(symbol, typeAtLocation, typeChecker); const fromReturnType = returnType && definitionFromType(returnType, typeChecker, node, failedAliasResolution); @@ -169826,8 +169922,7 @@ function tryGetReturnTypeOfFunction(symbol, type, checker) { if (type.symbol === symbol || // At `const f = () => {}`, the symbol is `f` and the type symbol is at `() => {}` symbol.valueDeclaration && type.symbol && isVariableDeclaration(symbol.valueDeclaration) && symbol.valueDeclaration.initializer === type.symbol.valueDeclaration) { const sigs = type.getCallSignatures(); - if (sigs.length === 1) - return checker.getReturnTypeOfSignature(first(sigs)); + if (sigs.length === 1) return checker.getReturnTypeOfSignature(first(sigs)); } return void 0; } @@ -169873,13 +169968,10 @@ function shouldSkipAlias(node, declaration) { return true; } function isExpandoDeclaration(node) { - if (!isAssignmentDeclaration(node)) - return false; + if (!isAssignmentDeclaration(node)) return false; const containingAssignment = findAncestor(node, (p) => { - if (isAssignmentExpression(p)) - return true; - if (!isAssignmentDeclaration(p)) - return "quit"; + if (isAssignmentExpression(p)) return true; + if (!isAssignmentDeclaration(p)) return "quit"; return false; }); return !!containingAssignment && getAssignmentDeclarationKind(containingAssignment) === 5 /* Property */; @@ -169984,19 +170076,15 @@ function createDefinitionInfoFromSwitch(statement, sourceFile) { }; } function isDefinitionVisible(checker, declaration) { - if (checker.isDeclarationVisible(declaration)) - return true; - if (!declaration.parent) - return false; - if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) - return isDefinitionVisible(checker, declaration.parent); + if (checker.isDeclarationVisible(declaration)) return true; + if (!declaration.parent) return false; + if (hasInitializer(declaration.parent) && declaration.parent.initializer === declaration) return isDefinitionVisible(checker, declaration.parent); switch (declaration.kind) { case 172 /* PropertyDeclaration */: case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: - if (hasEffectiveModifier(declaration, 2 /* Private */)) - return false; + if (hasEffectiveModifier(declaration, 2 /* Private */)) return false; case 176 /* Constructor */: case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: @@ -170045,10 +170133,11 @@ function tryGetSignatureDeclaration(typeChecker, node) { const signature = callLike && typeChecker.getResolvedSignature(callLike); return tryCast(signature && signature.declaration, (d) => isFunctionLike(d) && !isFunctionTypeNode(d)); } -function isConstructorLike(node) { +function isJsxConstructorLike(node) { switch (node.kind) { case 176 /* Constructor */: case 185 /* ConstructorType */: + case 179 /* CallSignature */: case 180 /* ConstructSignature */: return true; default: @@ -171076,11 +171165,9 @@ function getJSDocParameterNameCompletions(tag) { const nameThusFar = tag.name.text; const jsdoc = tag.parent; const fn = jsdoc.parent; - if (!isFunctionLike(fn)) - return []; + if (!isFunctionLike(fn)) return []; return mapDefined(fn.parameters, (param) => { - if (!isIdentifier(param.name)) - return void 0; + if (!isIdentifier(param.name)) return void 0; const name = param.name.text; if (jsdoc.tags.some((t) => t !== tag && isJSDocParameterTag(t) && isIdentifier(t.name) && t.name.escapedText === name) || nameThusFar !== void 0 && !startsWith(name, nameThusFar)) { return void 0; @@ -171137,8 +171224,7 @@ function getIndentationStringAtPosition(sourceFile, position) { const { text } = sourceFile; const lineStart = getLineStartPositionForPosition(position, sourceFile); let pos = lineStart; - for (; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) - ; + for (; pos <= position && isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) ; return text.slice(lineStart, pos); } function parameterDocComments(parameters, isJavaScriptFile, indentationStr, newLine) { @@ -171218,6 +171304,213 @@ function getRightHandSideOfAssignment(rightHandSide) { } } +// src/services/_namespaces/ts.MapCode.ts +var ts_MapCode_exports = {}; +__export(ts_MapCode_exports, { + mapCode: () => mapCode +}); + +// src/services/mapCode.ts +function mapCode(sourceFile, contents, focusLocations, host, formatContext, preferences) { + return ts_textChanges_exports.ChangeTracker.with( + { host, formatContext, preferences }, + (changeTracker) => { + const parsed = contents.map((c) => parse(sourceFile, c)); + const flattenedLocations = focusLocations && flatten(focusLocations); + for (const nodes of parsed) { + placeNodeGroup( + sourceFile, + changeTracker, + nodes, + flattenedLocations + ); + } + } + ); +} +function parse(sourceFile, content) { + const nodeKinds = [ + { + parse: () => createSourceFile( + "__mapcode_content_nodes.ts", + content, + sourceFile.languageVersion, + /*setParentNodes*/ + true, + sourceFile.scriptKind + ), + body: (sf) => sf.statements + }, + { + parse: () => createSourceFile( + "__mapcode_class_content_nodes.ts", + `class __class { +${content} +}`, + sourceFile.languageVersion, + /*setParentNodes*/ + true, + sourceFile.scriptKind + ), + body: (cw) => cw.statements[0].members + } + ]; + const parsedNodes = []; + for (const { parse: parse2, body: body2 } of nodeKinds) { + const sourceFile2 = parse2(); + const bod = body2(sourceFile2); + if (bod.length && sourceFile2.parseDiagnostics.length === 0) { + return bod; + } else if (bod.length) { + parsedNodes.push({ sourceFile: sourceFile2, body: bod }); + } + } + const { body } = parsedNodes.sort( + (a, b) => a.sourceFile.parseDiagnostics.length - b.sourceFile.parseDiagnostics.length + )[0]; + return body; +} +function placeNodeGroup(originalFile, changeTracker, changes, focusLocations) { + if (isClassElement(changes[0]) || isTypeElement(changes[0])) { + placeClassNodeGroup( + originalFile, + changeTracker, + changes, + focusLocations + ); + } else { + placeStatements( + originalFile, + changeTracker, + changes, + focusLocations + ); + } +} +function placeClassNodeGroup(originalFile, changeTracker, changes, focusLocations) { + let classOrInterface; + if (!focusLocations || !focusLocations.length) { + classOrInterface = find(originalFile.statements, or(isClassLike, isInterfaceDeclaration)); + } else { + classOrInterface = forEach(focusLocations, (location) => findAncestor( + getTokenAtPosition(originalFile, location.start), + or(isClassLike, isInterfaceDeclaration) + )); + } + if (!classOrInterface) { + return; + } + const firstMatch = classOrInterface.members.find((member) => changes.some((change) => matchNode(change, member))); + if (firstMatch) { + const lastMatch = findLast( + classOrInterface.members, + (member) => changes.some((change) => matchNode(change, member)) + ); + forEach(changes, wipeNode); + changeTracker.replaceNodeRangeWithNodes( + originalFile, + firstMatch, + lastMatch, + changes + ); + return; + } + forEach(changes, wipeNode); + changeTracker.insertNodesAfter( + originalFile, + classOrInterface.members[classOrInterface.members.length - 1], + changes + ); +} +function placeStatements(originalFile, changeTracker, changes, focusLocations) { + if (!(focusLocations == null ? void 0 : focusLocations.length)) { + changeTracker.insertNodesAtEndOfFile( + originalFile, + changes, + /*blankLineBetween*/ + false + ); + return; + } + for (const location of focusLocations) { + const scope = findAncestor( + getTokenAtPosition(originalFile, location.start), + (block) => or(isBlock, isSourceFile)(block) && some(block.statements, (origStmt) => changes.some((newStmt) => matchNode(newStmt, origStmt))) + ); + if (scope) { + const start = scope.statements.find((stmt) => changes.some((node) => matchNode(node, stmt))); + if (start) { + const end = findLast(scope.statements, (stmt) => changes.some((node) => matchNode(node, stmt))); + forEach(changes, wipeNode); + changeTracker.replaceNodeRangeWithNodes( + originalFile, + start, + end, + changes + ); + return; + } + } + } + let scopeStatements = originalFile.statements; + for (const location of focusLocations) { + const block = findAncestor( + getTokenAtPosition(originalFile, location.start), + isBlock + ); + if (block) { + scopeStatements = block.statements; + break; + } + } + forEach(changes, wipeNode); + changeTracker.insertNodesAfter( + originalFile, + scopeStatements[scopeStatements.length - 1], + changes + ); +} +function matchNode(a, b) { + var _a, _b, _c, _d, _e, _f; + if (a.kind !== b.kind) { + return false; + } + if (a.kind === 176 /* Constructor */) { + return a.kind === b.kind; + } + if (isNamedDeclaration(a) && isNamedDeclaration(b)) { + return a.name.getText() === b.name.getText(); + } + if (isIfStatement(a) && isIfStatement(b)) { + return a.expression.getText() === b.expression.getText(); + } + if (isWhileStatement(a) && isWhileStatement(b)) { + return a.expression.getText() === b.expression.getText(); + } + if (isForStatement(a) && isForStatement(b)) { + return ((_a = a.initializer) == null ? void 0 : _a.getText()) === ((_b = b.initializer) == null ? void 0 : _b.getText()) && ((_c = a.incrementor) == null ? void 0 : _c.getText()) === ((_d = b.incrementor) == null ? void 0 : _d.getText()) && ((_e = a.condition) == null ? void 0 : _e.getText()) === ((_f = b.condition) == null ? void 0 : _f.getText()); + } + if (isForInOrOfStatement(a) && isForInOrOfStatement(b)) { + return a.expression.getText() === b.expression.getText() && a.initializer.getText() === b.initializer.getText(); + } + if (isLabeledStatement(a) && isLabeledStatement(b)) { + return a.label.getText() === b.label.getText(); + } + if (a.getText() === b.getText()) { + return true; + } + return false; +} +function wipeNode(node) { + resetNodePositions(node); + node.parent = void 0; +} +function resetNodePositions(node) { + node.pos = -1; + node.end = -1; + node.forEachChild(resetNodePositions); +} + // src/services/_namespaces/ts.OrganizeImports.ts var ts_OrganizeImports_exports = {}; __export(ts_OrganizeImports_exports, { @@ -171264,8 +171557,7 @@ function organizeImports(sourceFile, formatContext, host, program, preferences, getTopLevelExportGroups(sourceFile).forEach((exportGroupDecl) => organizeExportsWorker(exportGroupDecl, comparer.namedImportComparer)); } for (const ambientModule of sourceFile.statements.filter(isAmbientModule)) { - if (!ambientModule.body) - continue; + if (!ambientModule.body) continue; const ambientModuleImportGroupDecls = groupByNewlineContiguous(sourceFile, ambientModule.body.statements.filter(isImportDeclaration)); ambientModuleImportGroupDecls.forEach((importGroupDecl) => organizeImportsWorker(importGroupDecl, comparer)); if (mode !== "RemoveUnused" /* RemoveUnused */) { @@ -171313,12 +171605,9 @@ function organizeImports(sourceFile, formatContext, host, program, preferences, const detectedTypeOrder = comparer2.typeOrder ?? "last"; const specifierComparer = getNamedImportSpecifierComparer({ organizeImportsTypeOrder: detectedTypeOrder }, detectedNamedImportCaseComparer); const processImportsOfSameModuleSpecifier = (importGroup) => { - if (shouldRemove) - importGroup = removeUnusedImports(importGroup, sourceFile, program); - if (shouldCombine) - importGroup = coalesceImportsWorker(importGroup, detectedModuleCaseComparer, specifierComparer, sourceFile); - if (shouldSort) - importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, detectedModuleCaseComparer)); + if (shouldRemove) importGroup = removeUnusedImports(importGroup, sourceFile, program); + if (shouldCombine) importGroup = coalesceImportsWorker(importGroup, detectedModuleCaseComparer, specifierComparer, sourceFile); + if (shouldSort) importGroup = stableSort(importGroup, (s1, s2) => compareImportsOrRequireStatements(s1, s2, detectedModuleCaseComparer)); return importGroup; }; organizeDeclsWorker(oldImportDecls, processImportsOfSameModuleSpecifier); @@ -171704,15 +171993,13 @@ function detectNamedImportOrganizationBySort(originalGroups, comparersToTest, ty const importDeclsWithNamed = originalGroups.filter((i) => { var _a, _b; const namedImports = (_b = tryCast((_a = i.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements; - if (!(namedImports == null ? void 0 : namedImports.length)) - return false; + if (!(namedImports == null ? void 0 : namedImports.length)) return false; if (!bothNamedImports && namedImports.some((n) => n.isTypeOnly) && namedImports.some((n) => !n.isTypeOnly)) { bothNamedImports = true; } return true; }); - if (importDeclsWithNamed.length === 0) - return; + if (importDeclsWithNamed.length === 0) return; const namedImportsByDecl = importDeclsWithNamed.map((importDecl) => { var _a, _b; return (_b = tryCast((_a = importDecl.importClause) == null ? void 0 : _a.namedBindings, isNamedImports)) == null ? void 0 : _b.elements; @@ -171742,16 +172029,14 @@ function detectNamedImportOrganizationBySort(originalGroups, comparersToTest, ty } } } - outer: - for (const bestKey of typesToTest) { - const bestTypeOrder = bestKey; - for (const testKey of typesToTest) { - const testTypeOrder = testKey; - if (bestDiff[testTypeOrder] < bestDiff[bestTypeOrder]) - continue outer; - } - return { namedImportComparer: bestComparer[bestTypeOrder], typeOrder: bestTypeOrder, isSorted: bestDiff[bestTypeOrder] === 0 }; + outer: for (const bestKey of typesToTest) { + const bestTypeOrder = bestKey; + for (const testKey of typesToTest) { + const testTypeOrder = testKey; + if (bestDiff[testTypeOrder] < bestDiff[bestTypeOrder]) continue outer; } + return { namedImportComparer: bestComparer[bestTypeOrder], typeOrder: bestTypeOrder, isSorted: bestDiff[bestTypeOrder] === 0 }; + } return { namedImportComparer: bestComparer.last, typeOrder: "last", isSorted: bestDiff.last === 0 }; } function measureSortedness(arr, comparer) { @@ -171769,8 +172054,7 @@ function detectCaseSensitivityBySort(originalGroups, comparersToTest) { for (const curComparer of comparersToTest) { let diffOfCurrentComparer = 0; for (const listToSort of originalGroups) { - if (listToSort.length <= 1) - continue; + if (listToSort.length <= 1) continue; const diff = measureSortedness(listToSort, curComparer); diffOfCurrentComparer += diff; } @@ -171791,14 +172075,10 @@ function getImportKindOrder(s1) { var _a; switch (s1.kind) { case 272 /* ImportDeclaration */: - if (!s1.importClause) - return 0; - if (s1.importClause.isTypeOnly) - return 1; - if (((_a = s1.importClause.namedBindings) == null ? void 0 : _a.kind) === 274 /* NamespaceImport */) - return 2; - if (s1.importClause.name) - return 3; + if (!s1.importClause) return 0; + if (s1.importClause.isTypeOnly) return 1; + if (((_a = s1.importClause.namedBindings) == null ? void 0 : _a.kind) === 274 /* NamespaceImport */) return 2; + if (s1.importClause.name) return 3; return 4; case 271 /* ImportEqualsDeclaration */: return 5; @@ -171825,10 +172105,8 @@ function getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) { } function getOrganizeImportsLocale(preferences) { let locale = preferences.organizeImportsLocale; - if (locale === "auto") - locale = getUILocale(); - if (locale === void 0) - locale = "en"; + if (locale === "auto") locale = getUILocale(); + if (locale === void 0) locale = "en"; const supportedLocales = Intl.Collator.supportedLocalesOf(locale); const resolvedLocale = supportedLocales.length ? supportedLocales[0] : "en"; return resolvedLocale; @@ -171913,8 +172191,7 @@ function addNodeOutliningSpans(sourceFile, cancellationToken, out) { visitNode3(statements[current]); current++; } - if (current === n) - break; + if (current === n) break; const firstImport = current; while (current < n && isAnyImportSyntax(statements[current])) { visitNode3(statements[current]); @@ -171927,8 +172204,7 @@ function addNodeOutliningSpans(sourceFile, cancellationToken, out) { } function visitNode3(n2) { var _a; - if (depthRemaining === 0) - return; + if (depthRemaining === 0) return; cancellationToken.throwIfCancellationRequested(); if (isDeclaration(n2) || isVariableStatement(n2) || isReturnStatement(n2) || isCallOrNewExpression(n2) || n2.kind === 1 /* EndOfFileToken */) { addOutliningForLeadingCommentsForNode(n2, sourceFile, cancellationToken, out); @@ -171943,8 +172219,7 @@ function addNodeOutliningSpans(sourceFile, cancellationToken, out) { addOutliningForLeadingCommentsForPos(n2.members.end, sourceFile, cancellationToken, out); } const span = getOutliningSpanForNode(n2, sourceFile); - if (span) - out.push(span); + if (span) out.push(span); depthRemaining--; if (isCallExpression(n2)) { depthRemaining++; @@ -172005,8 +172280,7 @@ function isRegionDelimiter(lineText) { } function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken, out) { const comments = getLeadingCommentRanges(sourceFile.text, pos); - if (!comments) - return; + if (!comments) return; let firstSingleLineCommentStart = -1; let lastSingleLineCommentEnd = -1; let singleLineCommentCount = 0; @@ -172044,8 +172318,7 @@ function addOutliningForLeadingCommentsForPos(pos, sourceFile, cancellationToken } } function addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out) { - if (isJsxText(n)) - return; + if (isJsxText(n)) return; addOutliningForLeadingCommentsForPos(n.pos, sourceFile, cancellationToken, out); } function createOutliningSpanFromBounds(pos, end, kind) { @@ -172073,8 +172346,7 @@ function getOutliningSpanForNode(n, sourceFile) { return spanForNode(n.parent); } else if (tryStatement.finallyBlock === n) { const node = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile); - if (node) - return spanForNode(node); + if (node) return spanForNode(node); } default: return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */); @@ -172238,8 +172510,7 @@ function getOutliningSpanForNode(n, sourceFile) { return nodeArray.length ? createOutliningSpan(createTextSpanFromRange(nodeArray), "code" /* Code */) : void 0; } function spanForParenthesizedExpression(node) { - if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile)) - return void 0; + if (positionsAreOnSameLine(node.getStart(), node.getEnd(), sourceFile)) return void 0; const textSpan = createTextSpanFromBounds(node.getStart(), node.getEnd()); return createOutliningSpan(textSpan, "code" /* Code */, createTextSpanFromNode(node)); } @@ -172306,8 +172577,7 @@ function getRenameInfoForNode(node, typeChecker, sourceFile, program, preference return void 0; } const { declarations } = symbol; - if (!declarations || declarations.length === 0) - return; + if (!declarations || declarations.length === 0) return; if (declarations.some((declaration) => isDefinedInLibraryFile(program, declaration))) { return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); } @@ -172376,8 +172646,7 @@ function getRenameInfoForModule(node, sourceFile, moduleSymbol) { return getRenameInfoError(Diagnostics.You_cannot_rename_a_module_via_a_global_import); } const moduleSourceFile = moduleSymbol.declarations && find(moduleSymbol.declarations, isSourceFile); - if (!moduleSourceFile) - return void 0; + if (!moduleSourceFile) return void 0; const withoutIndex = endsWith(node.text, "/index") || endsWith(node.text, "/index.js") ? void 0 : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index"); const fileName = withoutIndex === void 0 ? moduleSourceFile.fileName : withoutIndex; const kind = withoutIndex === void 0 ? "module" /* moduleElement */ : "directory" /* directory */; @@ -172451,8 +172720,7 @@ function getSignatureHelpItems(program, sourceFile, position, triggerReason, can } const isManuallyInvoked = !!triggerReason && triggerReason.kind === "invoked"; const argumentInfo = getContainingArgumentInfo(startingToken, position, sourceFile, typeChecker, isManuallyInvoked); - if (!argumentInfo) - return void 0; + if (!argumentInfo) return void 0; cancellationToken.throwIfCancellationRequested(); const candidateInfo = getCandidateOrTypeInfo(argumentInfo, typeChecker, sourceFile, startingToken, onlyUseSyntacticOwners); cancellationToken.throwIfCancellationRequested(); @@ -172477,8 +172745,7 @@ function getCandidateOrTypeInfo({ invocation, argumentCount }, checker, sourceFi return void 0; } const candidates = getPossibleGenericSignatures(called, argumentCount, checker); - if (candidates.length !== 0) - return { kind: 0 /* Candidate */, candidates, resolvedSignature: first(candidates) }; + if (candidates.length !== 0) return { kind: 0 /* Candidate */, candidates, resolvedSignature: first(candidates) }; const symbol = checker.getSymbolAtLocation(called); return symbol && { kind: 1 /* Type */, symbol }; } @@ -172489,8 +172756,7 @@ function getCandidateOrTypeInfo({ invocation, argumentCount }, checker, sourceFi } } function isSyntacticOwner(startingToken, node, sourceFile) { - if (!isCallOrNewExpression(node)) - return false; + if (!isCallOrNewExpression(node)) return false; const invocationChildren = node.getChildren(sourceFile); switch (startingToken.kind) { case 21 /* OpenParenToken */: @@ -172506,8 +172772,7 @@ function isSyntacticOwner(startingToken, node, sourceFile) { } } function createJSSignatureHelpItems(argumentInfo, program, cancellationToken) { - if (argumentInfo.invocation.kind === 2 /* Contextual */) - return void 0; + if (argumentInfo.invocation.kind === 2 /* Contextual */) return void 0; const expression = getExpressionFromInvocation(argumentInfo.invocation); const name = isPropertyAccessExpression(expression) ? expression.name.text : void 0; const typeChecker = program.getTypeChecker(); @@ -172554,8 +172819,7 @@ function getArgumentInfoForCompletions(node, position, sourceFile, checker) { } function getArgumentOrParameterListInfo(node, position, sourceFile, checker) { const info = getArgumentOrParameterListAndIndex(node, sourceFile, checker); - if (!info) - return void 0; + if (!info) return void 0; const { list, argumentIndex } = info; const argumentCount = getArgumentCount(checker, list); if (argumentIndex !== 0) { @@ -172577,8 +172841,7 @@ function getImmediatelyContainingArgumentInfo(node, position, sourceFile, checke if (isCallOrNewExpression(parent2)) { const invocation = parent2; const info = getArgumentOrParameterListInfo(node, position, sourceFile, checker); - if (!info) - return void 0; + if (!info) return void 0; const { list, argumentIndex, argumentCount, argumentsSpan } = info; const isTypeParameterList = !!parent2.typeArguments && parent2.typeArguments.pos === list.pos; return { isTypeParameterList, invocation: { kind: 0 /* Call */, node: invocation }, argumentsSpan, argumentIndex, argumentCount }; @@ -172644,19 +172907,15 @@ function countBinaryExpressionParameters(b) { } function tryGetParameterInfo(startingToken, position, sourceFile, checker) { const node = getAdjustedNode(startingToken); - if (node === void 0) - return void 0; + if (node === void 0) return void 0; const info = getContextualSignatureLocationInfo(node, sourceFile, position, checker); - if (info === void 0) - return void 0; + if (info === void 0) return void 0; const { contextualType, argumentIndex, argumentCount, argumentsSpan } = info; const nonNullableContextualType = contextualType.getNonNullableType(); const symbol = nonNullableContextualType.symbol; - if (symbol === void 0) - return void 0; + if (symbol === void 0) return void 0; const signature = lastOrUndefined(nonNullableContextualType.getCallSignatures()); - if (signature === void 0) - return void 0; + if (signature === void 0) return void 0; const invocation = { kind: 2 /* Contextual */, signature, node: startingToken, symbol: chooseBetterSymbol(symbol) }; return { isTypeParameterList: false, invocation, argumentsSpan, argumentIndex, argumentCount }; } @@ -172677,8 +172936,7 @@ function getContextualSignatureLocationInfo(node, sourceFile, position, checker) case 218 /* FunctionExpression */: case 219 /* ArrowFunction */: const info = getArgumentOrParameterListInfo(node, position, sourceFile, checker); - if (!info) - return void 0; + if (!info) return void 0; const { argumentIndex, argumentCount, argumentsSpan } = info; const contextualType = isMethodDeclaration(parent2) ? checker.getContextualTypeForObjectLiteralElement(parent2) : checker.getContextualType(parent2); return contextualType && { contextualType, argumentIndex, argumentCount, argumentsSpan }; @@ -172876,8 +173134,7 @@ function createSignatureHelpItems(candidates, resolvedSignature, { isTypeParamet } function createTypeHelpItems(symbol, { argumentCount, argumentsSpan: applicableSpan, invocation, argumentIndex }, sourceFile, checker) { const typeParameters = checker.getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - if (!typeParameters) - return void 0; + if (!typeParameters) return void 0; const items = [getTypeHelpItem(symbol, typeParameters, checker, getEnclosingDeclarationFromInvocation(invocation), sourceFile)]; return { items, applicableSpan, selectedItemIndex: 0, argumentIndex, argumentCount }; } @@ -172991,8 +173248,7 @@ function getSmartSelectionRange(pos, sourceFile) { outer: while (true) { const children = getSelectionChildren(parentNode); - if (!children.length) - break; + if (!children.length) break; for (let i = 0; i < children.length; i++) { const prevNode = children[i - 1]; const node = children[i]; @@ -173198,20 +173454,13 @@ function getSymbolKind(typeChecker, symbol, location) { if (flags & 32 /* Class */) { return getDeclarationOfKind(symbol, 231 /* ClassExpression */) ? "local class" /* localClassElement */ : "class" /* classElement */; } - if (flags & 384 /* Enum */) - return "enum" /* enumElement */; - if (flags & 524288 /* TypeAlias */) - return "type" /* typeElement */; - if (flags & 64 /* Interface */) - return "interface" /* interfaceElement */; - if (flags & 262144 /* TypeParameter */) - return "type parameter" /* typeParameterElement */; - if (flags & 8 /* EnumMember */) - return "enum member" /* enumMemberElement */; - if (flags & 2097152 /* Alias */) - return "alias" /* alias */; - if (flags & 1536 /* Module */) - return "module" /* moduleElement */; + if (flags & 384 /* Enum */) return "enum" /* enumElement */; + if (flags & 524288 /* TypeAlias */) return "type" /* typeElement */; + if (flags & 64 /* Interface */) return "interface" /* interfaceElement */; + if (flags & 262144 /* TypeParameter */) return "type parameter" /* typeParameterElement */; + if (flags & 8 /* EnumMember */) return "enum member" /* enumMemberElement */; + if (flags & 2097152 /* Alias */) return "alias" /* alias */; + if (flags & 1536 /* Module */) return "module" /* moduleElement */; return result; } function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) { @@ -173243,18 +173492,12 @@ function getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeCheck } return isLocalVariableOrFunction(symbol) ? "local var" /* localVariableElement */ : "var" /* variableElement */; } - if (flags & 16 /* Function */) - return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; - if (flags & 32768 /* GetAccessor */) - return "getter" /* memberGetAccessorElement */; - if (flags & 65536 /* SetAccessor */) - return "setter" /* memberSetAccessorElement */; - if (flags & 8192 /* Method */) - return "method" /* memberFunctionElement */; - if (flags & 16384 /* Constructor */) - return "constructor" /* constructorImplementationElement */; - if (flags & 131072 /* Signature */) - return "index" /* indexSignatureElement */; + if (flags & 16 /* Function */) return isLocalVariableOrFunction(symbol) ? "local function" /* localFunctionElement */ : "function" /* functionElement */; + if (flags & 32768 /* GetAccessor */) return "getter" /* memberGetAccessorElement */; + if (flags & 65536 /* SetAccessor */) return "setter" /* memberSetAccessorElement */; + if (flags & 8192 /* Method */) return "method" /* memberFunctionElement */; + if (flags & 16384 /* Constructor */) return "constructor" /* constructorImplementationElement */; + if (flags & 131072 /* Signature */) return "index" /* indexSignatureElement */; if (flags & 4 /* Property */) { if (flags & 33554432 /* Transient */ && symbol.links.checkFlags & 6 /* Synthetic */) { const unionPropertyKind = forEach(typeChecker.getRootSymbols(symbol), (rootSymbol) => { @@ -173509,8 +173752,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symb writeTypeParametersOfSymbol(symbol.parent, enclosingDeclaration); } else { const decl = getDeclarationOfKind(symbol, 168 /* TypeParameter */); - if (decl === void 0) - return Debug.fail(); + if (decl === void 0) return Debug.fail(); const declaration = decl.parent; if (declaration) { if (isFunctionLike(declaration)) { @@ -173561,7 +173803,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKindWorker(typeChecker, symb typeChecker, resolvedSymbol, getSourceFileOfNode(resolvedNode), - resolvedNode, + enclosingDeclaration, declarationName, type, semanticMeaning, @@ -174231,8 +174473,7 @@ var ChangeTracker = class _ChangeTracker { const unmergedNewTags = newTags.filter( (newTag) => !oldTags.some((tag, i) => { const merged = tryMergeJsdocTags(tag, newTag); - if (merged) - oldTags[i] = merged; + if (merged) oldTags[i] = merged; return !!merged; }) ); @@ -174253,8 +174494,7 @@ var ChangeTracker = class _ChangeTracker { if (isFunctionLike(node)) { endNode2 = findChildOfKind(node, 22 /* CloseParenToken */, sourceFile); if (!endNode2) { - if (!isArrowFunction(node)) - return false; + if (!isArrowFunction(node)) return false; endNode2 = first(node.parameters); } } else { @@ -174552,8 +174792,7 @@ ${options.prefix}` : "\n" : options.prefix deletedNodesInLists.forEach((node) => { const sourceFile = node.getSourceFile(); const list = ts_formatting_exports.SmartIndenter.getContainingList(node, sourceFile); - if (node !== last(list)) - return; + if (node !== last(list)) return; const lastNonDeletedIndex = findLastIndex(list, (n) => !deletedNodesInLists.has(n), list.length - 2); if (lastNonDeletedIndex !== -1) { this.deleteRange(sourceFile, { pos: list[lastNonDeletedIndex].end, end: startPositionToDeleteNodeInList(sourceFile, list[lastNonDeletedIndex + 1]) }); @@ -174726,8 +174965,7 @@ var changesToText; } function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); - if (validate) - validate(node, text); + if (validate) validate(node, text); const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === void 0) { @@ -175017,8 +175255,7 @@ function getInsertionPositionAtSourceFileTop(sourceFile) { advancePastLineBreak(); } const ranges = getLeadingCommentRanges(text, position); - if (!ranges) - return position; + if (!ranges) return position; let lastComment; let firstNodeLine; for (const range of ranges) { @@ -175032,19 +175269,15 @@ function getInsertionPositionAtSourceFileTop(sourceFile) { continue; } if (lastComment) { - if (lastComment.pinnedOrTripleSlash) - break; + if (lastComment.pinnedOrTripleSlash) break; const commentLine = sourceFile.getLineAndCharacterOfPosition(range.pos).line; const lastCommentEndLine = sourceFile.getLineAndCharacterOfPosition(lastComment.range.end).line; - if (commentLine >= lastCommentEndLine + 2) - break; + if (commentLine >= lastCommentEndLine + 2) break; } if (sourceFile.statements.length) { - if (firstNodeLine === void 0) - firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line; + if (firstNodeLine === void 0) firstNodeLine = sourceFile.getLineAndCharacterOfPosition(sourceFile.statements[0].getStart()).line; const commentEndLine = sourceFile.getLineAndCharacterOfPosition(range.end).line; - if (firstNodeLine < commentEndLine + 2) - break; + if (firstNodeLine < commentEndLine + 2) break; } lastComment = { range, pinnedOrTripleSlash: false }; } @@ -176696,8 +176929,7 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt function getFirstNonDecoratorTokenOfNode(node) { if (canHaveModifiers(node)) { const modifier = find(node.modifiers, isModifier, findIndex(node.modifiers, isDecorator)); - if (modifier) - return modifier.kind; + if (modifier) return modifier.kind; } switch (node.kind) { case 263 /* ClassDeclaration */: @@ -177147,8 +177379,7 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt if (indentFinalLine) { parts.push({ pos: startPos, end: commentRange.end }); } - if (parts.length === 0) - return; + if (parts.length === 0) return; const startLinePos = getStartPositionOfLine(startLine, sourceFile); const nonWhitespaceColumnInFirstPart = SmartIndenter.findFirstNonWhitespaceCharacterAndColumn(startLinePos, parts[0].pos, sourceFile, options); let startIndex = 0; @@ -177269,8 +177500,7 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt } function getRangeOfEnclosingComment(sourceFile, position, precedingToken, tokenAtPosition = getTokenAtPosition(sourceFile, position)) { const jsdoc = findAncestor(tokenAtPosition, isJSDoc); - if (jsdoc) - tokenAtPosition = jsdoc.parent; + if (jsdoc) tokenAtPosition = jsdoc.parent; const tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { return void 0; @@ -177646,14 +177876,11 @@ var SmartIndenter; SmartIndenter2.childIsUnindentedBranchOfConditionalExpression = childIsUnindentedBranchOfConditionalExpression; function argumentStartsOnSameLineAsPreviousArgument(parent2, child, childStartLine, sourceFile) { if (isCallOrNewExpression(parent2)) { - if (!parent2.arguments) - return false; + if (!parent2.arguments) return false; const currentNode = find(parent2.arguments, (arg) => arg.pos === child.pos); - if (!currentNode) - return false; + if (!currentNode) return false; const currentIndex = parent2.arguments.indexOf(currentNode); - if (currentIndex === 0) - return false; + if (currentIndex === 0) return false; const previousNode = parent2.arguments[currentIndex - 1]; const lineOfPreviousNode = getLineAndCharacterOfPosition(sourceFile, previousNode.getEnd()).line; if (childStartLine === lineOfPreviousNode) { @@ -177919,6 +178146,86 @@ var SmartIndenter; } })(SmartIndenter || (SmartIndenter = {})); +// src/services/_namespaces/ts.PasteEdits.ts +var ts_PasteEdits_exports = {}; +__export(ts_PasteEdits_exports, { + pasteEditsProvider: () => pasteEditsProvider +}); + +// src/services/pasteEdits.ts +var fixId54 = "providePostPasteEdits"; +function pasteEditsProvider(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken) { + const changes = ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changeTracker)); + return { edits: changes, fixId: fixId54 }; +} +function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changes) { + let actualPastedText; + if (pastedText.length !== pasteLocations.length) { + actualPastedText = pastedText.length === 1 ? pastedText : [pastedText.join("\n")]; + } + const statements = []; + let newText = targetFile.text; + for (let i = pasteLocations.length - 1; i >= 0; i--) { + const { pos, end } = pasteLocations[i]; + newText = actualPastedText ? newText.slice(0, pos) + actualPastedText[0] + newText.slice(end) : newText.slice(0, pos) + pastedText[i] + newText.slice(end); + } + Debug.checkDefined(host.runWithTemporaryFileUpdate).call(host, targetFile.fileName, newText, (updatedProgram, originalProgram, updatedFile) => { + const importAdder = ts_codefix_exports.createImportAdder(updatedFile, updatedProgram, preferences, host); + if (copiedFrom == null ? void 0 : copiedFrom.range) { + Debug.assert(copiedFrom.range.length === pastedText.length); + copiedFrom.range.forEach((copy) => { + const statementsInSourceFile = copiedFrom.file.statements; + const startNodeIndex = findIndex(statementsInSourceFile, (s) => s.end > copy.pos); + if (startNodeIndex === -1) return void 0; + let endNodeIndex = findIndex(statementsInSourceFile, (s) => s.end >= copy.end, startNodeIndex); + if (endNodeIndex !== -1 && copy.end <= statementsInSourceFile[endNodeIndex].getStart()) { + endNodeIndex--; + } + statements.push(...statementsInSourceFile.slice(startNodeIndex, endNodeIndex === -1 ? statementsInSourceFile.length : endNodeIndex + 1)); + }); + const usage = getUsageInfo(copiedFrom.file, statements, originalProgram.getTypeChecker(), getExistingLocals(updatedFile, statements, originalProgram.getTypeChecker())); + Debug.assertIsDefined(originalProgram); + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, originalProgram, host, !!copiedFrom.file.commonJsModuleIndicator); + addExportsInOldFile(copiedFrom.file, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax); + addTargetFileImports(copiedFrom.file, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, originalProgram.getTypeChecker(), updatedProgram, importAdder); + } else { + const context = { + sourceFile: updatedFile, + program: originalProgram, + cancellationToken, + host, + preferences, + formatContext + }; + forEachChild(updatedFile, function cb(node) { + if (isIdentifier(node) && !(originalProgram == null ? void 0 : originalProgram.getTypeChecker().resolveName( + node.text, + node, + -1 /* All */, + /*excludeGlobals*/ + false + ))) { + importAdder.addImportForUnresolvedIdentifier( + context, + node, + /*useAutoImportProvider*/ + true + ); + } + node.forEachChild(cb); + }); + } + importAdder.writeFixes(changes, getQuotePreference(copiedFrom ? copiedFrom.file : targetFile, preferences)); + }); + pasteLocations.forEach((paste, i) => { + changes.replaceRangeWithText( + targetFile, + { pos: paste.pos, end: paste.end }, + actualPastedText ? actualPastedText[0] : pastedText[i] + ); + }); +} + // src/server/_namespaces/ts.ts var ts_exports2 = {}; __export(ts_exports2, { @@ -177954,7 +178261,6 @@ __export(ts_exports2, { EmitHint: () => EmitHint, EmitOnly: () => EmitOnly, EndOfLineState: () => EndOfLineState, - EnumKind: () => EnumKind, ExitStatus: () => ExitStatus, ExportKind: () => ExportKind, Extension: () => Extension, @@ -177981,10 +178287,11 @@ __export(ts_exports2, { IndexKind: () => IndexKind, InferenceFlags: () => InferenceFlags, InferencePriority: () => InferencePriority, - InlayHintKind: () => InlayHintKind, + InlayHintKind: () => InlayHintKind2, InlayHints: () => ts_InlayHints_exports, InternalEmitFlags: () => InternalEmitFlags, InternalSymbolName: () => InternalSymbolName, + IntersectionFlags: () => IntersectionFlags, InvalidatedProjectKind: () => InvalidatedProjectKind, JSDocParsingMode: () => JSDocParsingMode, JsDoc: () => ts_JsDoc_exports, @@ -177998,6 +178305,7 @@ __export(ts_exports2, { LexicalEnvironmentFlags: () => LexicalEnvironmentFlags, ListFormat: () => ListFormat, LogLevel: () => LogLevel, + MapCode: () => ts_MapCode_exports, MemberOverrideStatus: () => MemberOverrideStatus, ModifierFlags: () => ModifierFlags, ModuleDetectionKind: () => ModuleDetectionKind, @@ -178145,6 +178453,7 @@ __export(ts_exports2, { canHaveModifiers: () => canHaveModifiers, canHaveModuleSpecifier: () => canHaveModuleSpecifier, canHaveSymbol: () => canHaveSymbol, + canIncludeBindAndCheckDiagnsotics: () => canIncludeBindAndCheckDiagnsotics, canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, canProduceDiagnostics: () => canProduceDiagnostics, canUsePropertyAccess: () => canUsePropertyAccess, @@ -178188,6 +178497,7 @@ __export(ts_exports2, { collectExternalModuleInfo: () => collectExternalModuleInfo, combine: () => combine, combinePaths: () => combinePaths, + commandLineOptionOfCustomType: () => commandLineOptionOfCustomType, commentPragmas: () => commentPragmas, commonOptionsWithBuild: () => commonOptionsWithBuild, commonPackageFolders: () => commonPackageFolders, @@ -178397,6 +178707,7 @@ __export(ts_exports2, { defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, diagnosticCategoryName: () => diagnosticCategoryName, diagnosticToString: () => diagnosticToString, + diagnosticsEqualityComparer: () => diagnosticsEqualityComparer, directoryProbablyExists: () => directoryProbablyExists, directorySeparator: () => directorySeparator, displayPart: () => displayPart, @@ -178416,6 +178727,7 @@ __export(ts_exports2, { emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, emitNewLineBeforeLeadingComments: () => emitNewLineBeforeLeadingComments, emitNewLineBeforeLeadingCommentsOfPosition: () => emitNewLineBeforeLeadingCommentsOfPosition, + emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking, emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, emptyArray: () => emptyArray, emptyFileSystemEntries: () => emptyFileSystemEntries, @@ -178515,6 +178827,7 @@ __export(ts_exports2, { forEachKey: () => forEachKey, forEachLeadingCommentRange: () => forEachLeadingCommentRange, forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft, + forEachNameOfDefaultExport: () => forEachNameOfDefaultExport, forEachPropertyAssignment: () => forEachPropertyAssignment, forEachResolvedProjectReference: () => forEachResolvedProjectReference, forEachReturnStatement: () => forEachReturnStatement, @@ -178570,6 +178883,7 @@ __export(ts_exports2, { getBuildOrderFromAnyBuildOrder: () => getBuildOrderFromAnyBuildOrder, getBuilderCreationParameters: () => getBuilderCreationParameters, getBuilderFileEmit: () => getBuilderFileEmit, + getCanonicalDiagnostic: () => getCanonicalDiagnostic, getCheckFlags: () => getCheckFlags, getClassExtendsHeritageElement: () => getClassExtendsHeritageElement, getClassLikeDeclarationOfSymbol: () => getClassLikeDeclarationOfSymbol, @@ -178610,11 +178924,11 @@ __export(ts_exports2, { getDeclaredExpandoInitializer: () => getDeclaredExpandoInitializer, getDecorators: () => getDecorators, getDefaultCompilerOptions: () => getDefaultCompilerOptions2, - getDefaultExportInfoWorker: () => getDefaultExportInfoWorker, getDefaultFormatCodeSettings: () => getDefaultFormatCodeSettings, getDefaultLibFileName: () => getDefaultLibFileName, getDefaultLibFilePath: () => getDefaultLibFilePath, getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, + getDefaultLikeExportNameFromDeclaration: () => getDefaultLikeExportNameFromDeclaration, getDefaultResolutionModeForFileWorker: () => getDefaultResolutionModeForFileWorker, getDiagnosticText: () => getDiagnosticText, getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, @@ -178949,6 +179263,7 @@ __export(ts_exports2, { getSwitchedType: () => getSwitchedType, getSymbolId: () => getSymbolId, getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, + getSymbolParentOrFail: () => getSymbolParentOrFail, getSymbolTarget: () => getSymbolTarget, getSyntacticClassifications: () => getSyntacticClassifications, getSyntacticModifierFlags: () => getSyntacticModifierFlags, @@ -179780,7 +180095,6 @@ __export(ts_exports2, { loadWithModeAwareCache: () => loadWithModeAwareCache, makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, makeImport: () => makeImport, - makeImportIfNecessary: () => makeImportIfNecessary, makeStringLiteral: () => makeStringLiteral, mangleScopedPackageName: () => mangleScopedPackageName, map: () => map, @@ -179814,7 +180128,9 @@ __export(ts_exports2, { moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations, moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports, moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules, + moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier, moduleSpecifiers: () => ts_moduleSpecifiers_exports, + moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier, moveEmitHelpers: () => moveEmitHelpers, moveRangeEnd: () => moveRangeEnd, moveRangePastDecorators: () => moveRangePastDecorators, @@ -179894,6 +180210,7 @@ __export(ts_exports2, { parsePackageName: () => parsePackageName, parsePseudoBigInt: () => parsePseudoBigInt, parseValidBigInt: () => parseValidBigInt, + pasteEdits: () => ts_PasteEdits_exports, patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory, pathContainsNodeModules: () => pathContainsNodeModules, pathIsAbsolute: () => pathIsAbsolute, @@ -180367,6 +180684,7 @@ __export(ts_server_exports3, { CommandNames: () => CommandNames, ConfigFileDiagEvent: () => ConfigFileDiagEvent, ConfiguredProject: () => ConfiguredProject2, + ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind, CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, CreateFileWatcherEvent: () => CreateFileWatcherEvent, Errors: () => Errors, @@ -180374,7 +180692,7 @@ __export(ts_server_exports3, { EventEndInstallTypes: () => EventEndInstallTypes, EventInitializationFailed: () => EventInitializationFailed, EventTypesRegistry: () => EventTypesRegistry, - ExternalProject: () => ExternalProject2, + ExternalProject: () => ExternalProject, GcTimer: () => GcTimer, InferredProject: () => InferredProject2, LargeFileReferencedEvent: () => LargeFileReferencedEvent, @@ -180390,7 +180708,6 @@ __export(ts_server_exports3, { ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind, ProjectService: () => ProjectService3, ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, ScriptInfo: () => ScriptInfo, @@ -180442,7 +180759,6 @@ __export(ts_server_exports3, { nowString: () => nowString, nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, - projectContainsInfoDirectly: () => projectContainsInfoDirectly, protocol: () => ts_server_protocol_exports, removeSorted: () => removeSorted, stringifyIndented: () => stringifyIndented, @@ -180714,25 +181030,21 @@ var TypingsInstaller = class { return mapDefined(typingsToInstall, (typing) => { const typingKey = mangleScopedPackageName(typing); if (this.missingTypingsSet.has(typingKey)) { - if (this.log.isEnabled()) - this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`); + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`); return void 0; } const validationResult = ts_JsTyping_exports.validatePackageName(typing); if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) { this.missingTypingsSet.add(typingKey); - if (this.log.isEnabled()) - this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing)); + if (this.log.isEnabled()) this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing)); return void 0; } if (!this.typesRegistry.has(typingKey)) { - if (this.log.isEnabled()) - this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`); + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`); return void 0; } if (this.packageNameToTypingLocation.get(typingKey) && ts_JsTyping_exports.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey), this.typesRegistry.get(typingKey))) { - if (this.log.isEnabled()) - this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`); + if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`); return void 0; } return typingKey; @@ -180985,8 +181297,7 @@ var ThrottledOperations = class _ThrottledOperations { } cancel(operationId) { const pendingTimeout = this.pendingTimeouts.get(operationId); - if (!pendingTimeout) - return false; + if (!pendingTimeout) return false; this.host.clearTimeout(pendingTimeout); return this.pendingTimeouts.delete(operationId); } @@ -181155,6 +181466,7 @@ var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; + CommandTypes2["GetPasteEdits"] = "getPasteEdits"; CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; CommandTypes2["OrganizeImports"] = "organizeImports"; CommandTypes2["OrganizeImportsFull"] = "organizeImports-full"; @@ -181176,6 +181488,7 @@ var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { CommandTypes2["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls"; CommandTypes2["ProvideInlayHints"] = "provideInlayHints"; CommandTypes2["WatchChange"] = "watchChange"; + CommandTypes2["MapCode"] = "mapCode"; return CommandTypes2; })(CommandTypes || {}); var WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => { @@ -181377,8 +181690,7 @@ var TextStorage = class { } getAbsolutePositionAndLineText(oneBasedLine) { const svc = this.tryUseScriptVersionCache(); - if (svc) - return svc.getAbsolutePositionAndLineText(oneBasedLine); + if (svc) return svc.getAbsolutePositionAndLineText(oneBasedLine); const lineMap = this.getLineMap(); return oneBasedLine <= lineMap.length ? { absolutePosition: lineMap[oneBasedLine - 1], @@ -181393,8 +181705,7 @@ var TextStorage = class { */ lineToTextSpan(line) { const svc = this.tryUseScriptVersionCache(); - if (svc) - return svc.lineToTextSpan(line); + if (svc) return svc.lineToTextSpan(line); const lineMap = this.getLineMap(); const start = lineMap[line]; const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; @@ -181410,8 +181721,7 @@ var TextStorage = class { } positionToLineOffset(position) { const svc = this.tryUseScriptVersionCache(); - if (svc) - return svc.positionToLineOffset(position); + if (svc) return svc.positionToLineOffset(position); const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position); return { line: line + 1, offset: character + 1 }; } @@ -181627,11 +181937,8 @@ var ScriptInfo = class { case 0: return Errors.ThrowNoProject(); case 1: - return ensurePrimaryProjectKind( - !isProjectDeferredClose(this.containingProjects[0]) ? this.containingProjects[0] : void 0 - ); + return isProjectDeferredClose(this.containingProjects[0]) || isBackgroundProject(this.containingProjects[0]) ? Errors.ThrowNoProject() : this.containingProjects[0]; default: - let firstExternalProject; let firstConfiguredProject; let firstInferredProject; let firstNonSourceOfProjectReferenceRedirect; @@ -181639,28 +181946,22 @@ var ScriptInfo = class { for (let index = 0; index < this.containingProjects.length; index++) { const project = this.containingProjects[index]; if (isConfiguredProject(project)) { - if (project.deferredClose) - continue; + if (project.deferredClose) continue; if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { if (defaultConfiguredProject === void 0 && index !== this.containingProjects.length - 1) { defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; } - if (defaultConfiguredProject === project) - return project; - if (!firstNonSourceOfProjectReferenceRedirect) - firstNonSourceOfProjectReferenceRedirect = project; - } - if (!firstConfiguredProject) - firstConfiguredProject = project; - } else if (!firstExternalProject && isExternalProject(project)) { - firstExternalProject = project; + if (defaultConfiguredProject === project) return project; + if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project; + } + if (!firstConfiguredProject) firstConfiguredProject = project; + } else if (isExternalProject(project)) { + return project; } else if (!firstInferredProject && isInferredProject(project)) { firstInferredProject = project; } } - return ensurePrimaryProjectKind( - defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstExternalProject || firstInferredProject - ); + return (defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstInferredProject) ?? Errors.ThrowNoProject(); } } registerFileUpdate() { @@ -181750,12 +182051,6 @@ var ScriptInfo = class { } } }; -function ensurePrimaryProjectKind(project) { - if (!project || isBackgroundProject(project)) { - return Errors.ThrowNoProject(); - } - return project; -} function failIfInvalidPosition(position) { Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`); Debug.assert(position >= 0, `Expected position to be non-negative.`); @@ -181946,7 +182241,6 @@ var Project3 = class _Project { this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; this.watchOptions = watchOptions; - this.rootFiles = []; this.rootFilesMap = /* @__PURE__ */ new Map(); /** @internal */ this.plugins = []; @@ -182148,7 +182442,7 @@ var Project3 = class _Project { return void 0; } getScriptFileNames() { - if (!this.rootFiles) { + if (!this.rootFilesMap.size) { return emptyArray; } let result; @@ -182170,7 +182464,6 @@ var Project3 = class _Project { if (scriptInfo) { const existingValue = this.rootFilesMap.get(scriptInfo.path); if (existingValue && existingValue.info !== scriptInfo) { - this.rootFiles.push(scriptInfo); existingValue.info = scriptInfo; } scriptInfo.attachToProject(this); @@ -182495,8 +182788,7 @@ var Project3 = class _Project { } getExternalFiles(updateLevel) { return sort(flatMap(this.plugins, (plugin) => { - if (typeof plugin.module.getExternalFiles !== "function") - return; + if (typeof plugin.module.getExternalFiles !== "function") return; try { return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */); } catch (e) { @@ -182524,11 +182816,11 @@ var Project3 = class _Project { this.closeWatchingTypingLocations(); this.cleanupProgram(); forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile)); - for (const root of this.rootFiles) { - root.detachFromProject(this); - } + this.rootFilesMap.forEach((root) => { + var _a2; + return (_a2 = root.info) == null ? void 0 : _a2.detachFromProject(this); + }); this.projectService.pendingEnsureProjectForOpenFiles = true; - this.rootFiles = void 0; this.rootFilesMap = void 0; this.externalFiles = void 0; this.program = void 0; @@ -182571,28 +182863,32 @@ var Project3 = class _Project { } } isClosed() { - return this.rootFiles === void 0; + return this.rootFilesMap === void 0; } hasRoots() { - return this.rootFiles && this.rootFiles.length > 0; + var _a; + return !!((_a = this.rootFilesMap) == null ? void 0 : _a.size); } /** @internal */ isOrphan() { return false; } getRootFiles() { - return this.rootFiles && this.rootFiles.map((info) => info.fileName); + return this.rootFilesMap && arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => { + var _a; + return (_a = value.info) == null ? void 0 : _a.fileName; + })); } /** @internal */ getRootFilesMap() { return this.rootFilesMap; } getRootScriptInfos() { - return this.rootFiles; + return arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => value.info)); } getScriptInfos() { if (!this.languageServiceEnabled) { - return this.rootFiles; + return this.getRootScriptInfos(); } return map(this.program.getSourceFiles(), (sourceFile) => { const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); @@ -182663,10 +182959,8 @@ var Project3 = class _Project { return false; } containsScriptInfo(info) { - if (this.isRoot(info)) - return true; - if (!this.program) - return false; + if (this.isRoot(info)) return true; + if (!this.program) return false; const file = this.program.getSourceFileByPath(info.path); return !!file && file.resolvedPath === info.path; } @@ -182678,13 +182972,12 @@ var Project3 = class _Project { return false; } isRoot(info) { - var _a; - return this.rootFilesMap && ((_a = this.rootFilesMap.get(info.path)) == null ? void 0 : _a.info) === info; + var _a, _b; + return ((_b = (_a = this.rootFilesMap) == null ? void 0 : _a.get(info.path)) == null ? void 0 : _b.info) === info; } // add a root file to project addRoot(info, fileName) { Debug.assert(!this.isRoot(info)); - this.rootFiles.push(info); this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info }); info.attachToProject(this); this.markAsDirty(); @@ -182730,8 +183023,7 @@ var Project3 = class _Project { /** @internal */ markAutoImportProviderAsDirty() { var _a; - if (!this.autoImportProviderHost) - this.autoImportProviderHost = void 0; + if (!this.autoImportProviderHost) this.autoImportProviderHost = void 0; (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty(); } /** @internal */ @@ -182821,8 +183113,7 @@ var Project3 = class _Project { } /** @internal */ closeWatchingTypingLocations() { - if (this.typingWatchers) - clearMap(this.typingWatchers, closeFileWatcher); + if (this.typingWatchers) clearMap(this.typingWatchers, closeFileWatcher); this.typingWatchers = void 0; } /** @internal */ @@ -182841,8 +183132,7 @@ var Project3 = class _Project { return; } const toRemove = new Map(this.typingWatchers); - if (!this.typingWatchers) - this.typingWatchers = /* @__PURE__ */ new Map(); + if (!this.typingWatchers) this.typingWatchers = /* @__PURE__ */ new Map(); this.typingWatchers.isInvoked = false; const createProjectWatcher = (path, typingsWatcherType) => { const canonicalPath = this.toPath(path); @@ -182860,12 +183150,9 @@ var Project3 = class _Project { ) : this.projectService.watchFactory.watchDirectory( path, (f) => { - if (this.typingWatchers.isInvoked) - return this.writeLog(`TypingWatchers already invoked`); - if (!fileExtensionIs(f, ".json" /* Json */)) - return this.writeLog(`Ignoring files that are not *.json`); - if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames())) - return this.writeLog(`Ignoring package.json change at global typings location`); + if (this.typingWatchers.isInvoked) return this.writeLog(`TypingWatchers already invoked`); + if (!fileExtensionIs(f, ".json" /* Json */)) return this.writeLog(`Ignoring files that are not *.json`); + if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames())) return this.writeLog(`Ignoring package.json change at global typings location`); this.onTypingInstallerWatchInvoke(); }, 1 /* Recursive */, @@ -182956,6 +183243,15 @@ var Project3 = class _Project { } }); } + this.rootFilesMap.forEach((value, path) => { + var _a2; + const file = this.program.getSourceFileByPath(path); + const info = value.info; + if (!file || ((_a2 = value.info) == null ? void 0 : _a2.path) === file.resolvedPath) return; + value.info = this.projectService.getScriptInfo(file.fileName); + Debug.assert(value.info.isAttached(this)); + info == null ? void 0 : info.detachFromProject(this); + }); updateMissingFilePathsWatch( this.program, this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()), @@ -183084,8 +183380,7 @@ var Project3 = class _Project { var _a; if (isConfiguredProject(this)) { const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath); - if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) - return noopFileWatcher; + if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) return noopFileWatcher; } const fileWatcher = this.projectService.watchFactory.watchFile( getNormalizedAbsolutePath(missingFileName, this.currentDirectory), @@ -183122,8 +183417,7 @@ var Project3 = class _Project { Debug.fail(`${this.projectName} Expected to not have --out watcher for generated file with options: ${JSON.stringify(this.compilerOptions)}`); return; } - if (this.generatedFilesMap.has(path)) - return; + if (this.generatedFilesMap.has(path)) return; } else { this.generatedFilesMap = /* @__PURE__ */ new Map(); } @@ -183180,10 +183474,8 @@ var Project3 = class _Project { } /** @internal */ filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { - if (this.isInitialLoadPending()) - return " Files (0) InitialLoadPending\n"; - if (!this.program) - return " Files (0) NoProgram\n"; + if (this.isInitialLoadPending()) return " Files (0) InitialLoadPending\n"; + if (!this.program) return " Files (0) NoProgram\n"; const sourceFiles = this.program.getSourceFiles(); let strBuilder = ` Files (${sourceFiles.length}) `; @@ -183352,7 +183644,6 @@ var Project3 = class _Project { } // remove a root file from project removeRoot(info) { - orderedRemoveItem(this.rootFiles, info); this.rootFilesMap.delete(info.path); } /** @internal */ @@ -183368,8 +183659,7 @@ var Project3 = class _Project { ]; } enableGlobalPlugins(options) { - if (!this.projectService.globalPlugins.length) - return; + if (!this.projectService.globalPlugins.length) return; const host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); @@ -183377,10 +183667,8 @@ var Project3 = class _Project { } const searchPaths = this.getGlobalPluginSearchPaths(); for (const globalPluginName of this.projectService.globalPlugins) { - if (!globalPluginName) - continue; - if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) - continue; + if (!globalPluginName) continue; + if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) continue; this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); this.enablePlugin({ name: globalPluginName, global: true }, searchPaths); } @@ -183432,8 +183720,7 @@ var Project3 = class _Project { } /** @internal */ getPackageJsonsVisibleToFile(fileName, rootDir) { - if (this.projectService.serverMode !== 0 /* Semantic */) - return emptyArray2; + if (this.projectService.serverMode !== 0 /* Semantic */) return emptyArray2; return this.projectService.getPackageJsonsVisibleToFile(fileName, this, rootDir); } /** @internal */ @@ -183523,7 +183810,7 @@ var Project3 = class _Project { isDefaultProjectForOpenFiles() { return !!forEachEntry( this.projectService.openFiles, - (_, fileName) => this.projectService.tryGetDefaultProjectForFile(toNormalizedPath(fileName)) === this + (_projectRootPath, path) => this.projectService.tryGetDefaultProjectForFile(this.projectService.getScriptInfoForPath(path)) === this ); } /** @internal */ @@ -183547,6 +183834,17 @@ var Project3 = class _Project { return this.noDtsResolutionProject; } /** @internal */ + runWithTemporaryFileUpdate(rootFile, updatedText, cb) { + var _a, _b, _c, _d; + const originalProgram = this.program; + const rootSourceFile = Debug.checkDefined((_a = this.program) == null ? void 0 : _a.getSourceFile(rootFile), "Expected file to be part of program"); + const originalText = Debug.checkDefined(rootSourceFile.getText()); + (_b = this.getScriptInfo(rootFile)) == null ? void 0 : _b.editContent(0, originalText.length, updatedText); + this.updateGraph(); + cb(this.program, originalProgram, (_c = this.program) == null ? void 0 : _c.getSourceFile(rootFile)); + (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, this.program.getSourceFile(rootFile).getText().length, originalText); + } + /** @internal */ getCompilerOptionsForNoDtsResolutionProject() { return { ...this.getCompilerOptions(), @@ -183651,7 +183949,7 @@ var InferredProject2 = class extends Project3 { super.addRoot(info); } removeRoot(info) { - this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); + this.projectService.stopWatchingConfigFilesForScriptInfo(info); super.removeRoot(info); if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { @@ -183670,7 +183968,7 @@ var InferredProject2 = class extends Project3 { return !this.projectRootPath && !this.projectService.useSingleInferredProject || this.getRootScriptInfos().length === 1; } close() { - forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info)); + forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForScriptInfo(info)); super.close(); } getTypeAcquisition() { @@ -183789,8 +184087,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec } } }); - if (done) - continue; + if (done) continue; if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) { const entrypoints = getRootNamesFromPackageJson( packageJson, @@ -183835,8 +184132,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec } return rootNames ? arrayFrom(rootNames.values()) : emptyArray; function addRootNames(entrypoints) { - if (!(entrypoints == null ? void 0 : entrypoints.length)) - return 0; + if (!(entrypoints == null ? void 0 : entrypoints.length)) return 0; rootNames ?? (rootNames = /* @__PURE__ */ new Set()); entrypoints.forEach((entry) => rootNames.add(entry)); return 1; @@ -183980,7 +184276,7 @@ _AutoImportProviderProject.compilerOptionsOverrides = { var AutoImportProviderProject = _AutoImportProviderProject; var ConfiguredProject2 = class extends Project3 { /** @internal */ - constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost) { + constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost, pendingUpdateReason) { super( configFileName, 1 /* Configured */, @@ -184004,12 +184300,12 @@ var ConfiguredProject2 = class extends Project3 { this.openFileWatchTriggered = /* @__PURE__ */ new Map(); /** @internal */ this.canConfigFileJsonReportNoInputFiles = false; - /** Ref count to the project when opened from external project */ - this.externalProjectRefCount = 0; /** @internal */ this.isInitialLoadPending = returnTrue; /** @internal */ this.sendLoadingProjectFinish = false; + this.pendingUpdateLevel = 2 /* Full */; + this.pendingUpdateReason = pendingUpdateReason; } /** @internal */ setCompilerHost(host) { @@ -184051,9 +184347,8 @@ var ConfiguredProject2 = class extends Project3 { * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph() { - if (this.deferredClose) - return false; - const isInitialLoad = this.isInitialLoadPending(); + if (this.deferredClose) return false; + const isDirty = this.dirty; this.isInitialLoadPending = returnFalse; const updateLevel = this.pendingUpdateLevel; this.pendingUpdateLevel = 0 /* Update */; @@ -184066,14 +184361,7 @@ var ConfiguredProject2 = class extends Project3 { case 2 /* Full */: this.openFileWatchTriggered.clear(); const reason = Debug.checkDefined(this.pendingUpdateReason); - this.pendingUpdateReason = void 0; - this.projectService.reloadConfiguredProject( - this, - reason, - isInitialLoad, - /*clearSemanticCache*/ - false - ); + this.projectService.reloadConfiguredProject(this, reason); result = true; break; default: @@ -184082,11 +184370,17 @@ var ConfiguredProject2 = class extends Project3 { this.compilerHost = void 0; this.projectService.sendProjectLoadingFinishEvent(this); this.projectService.sendProjectTelemetry(this); - if (!this.skipConfigDiagEvent && !result) { + if (updateLevel === 2 /* Full */ || // Already sent event through reload + result && // Not new program + (!isDirty || !this.triggerFileForConfigFileDiag || this.getCurrentProgram().structureIsReused === 2 /* Completely */)) { + this.triggerFileForConfigFileDiag = void 0; + } else if (!this.triggerFileForConfigFileDiag) { this.projectService.sendConfigFileDiagEvent( this, /*triggerFile*/ - void 0 + void 0, + /*force*/ + false ); } return result; @@ -184124,8 +184418,7 @@ var ConfiguredProject2 = class extends Project3 { enablePluginsWithOptions(options) { var _a; this.plugins.length = 0; - if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) - return; + if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) return; const host = this.projectService.host; if (!host.require && !host.importPlugin) { this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); @@ -184168,75 +184461,17 @@ var ConfiguredProject2 = class extends Project3 { } /** @internal */ markAsDirty() { - if (this.deferredClose) - return; + if (this.deferredClose) return; super.markAsDirty(); } /** @internal */ - addExternalProjectReference() { - this.externalProjectRefCount++; - } - /** @internal */ - deleteExternalProjectReference() { - this.externalProjectRefCount--; - } - /** @internal */ isSolution() { return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles; } - /** - * Find the configured project from the project references in project which contains the info directly - * - * @internal - */ - getDefaultChildProjectFromProjectWithReferences(info) { - return forEachResolvedProjectReferenceProject( - this, - info.path, - (child) => projectContainsInfoDirectly(child, info) ? child : void 0, - 0 /* Find */ - ); - } - /** - * Returns true if the project is needed by any of the open script info/external project - * - * @internal - */ - hasOpenRef() { - var _a, _b; - if (!!this.externalProjectRefCount) { - return true; - } - if (this.isClosed()) { - return false; - } - const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(this.canonicalConfigFilePath); - if (this.deferredClose) - return !!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.size); - if (this.projectService.hasPendingProjectUpdate(this)) { - return !!((_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.size); - } - return !!configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry( - configFileExistenceInfo.openFilesImpactedByConfigFile, - (_value, infoPath) => { - const info = this.projectService.getScriptInfoForPath(infoPath); - return this.containsScriptInfo(info) || !!forEachResolvedProjectReferenceProject( - this, - info.path, - (child) => child.containsScriptInfo(info), - 0 /* Find */ - ); - } - ) || false; - } /** @internal */ isOrphan() { return !!this.deferredClose; } - /** @internal */ - hasExternalProjectRef() { - return !!this.externalProjectRefCount; - } getEffectiveTypeRoots() { return getEffectiveTypeRoots(this.getCompilationSettings(), this) || []; } @@ -184245,7 +184480,7 @@ var ConfiguredProject2 = class extends Project3 { updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); } }; -var ExternalProject2 = class extends Project3 { +var ExternalProject = class extends Project3 { /** @internal */ constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { super( @@ -184383,8 +184618,7 @@ function convertWatchOptions(protocolOptions, currentDirectory) { let errors; optionsForWatch.forEach((option) => { const propertyValue = protocolOptions[option.name]; - if (propertyValue === void 0) - return; + if (propertyValue === void 0) return; const mappedValues = watchOptionsConverters.get(option.name); (watchOptions || (watchOptions = {}))[option.name] = mappedValues ? isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue : convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = [])); }); @@ -184394,8 +184628,7 @@ function convertTypeAcquisition(protocolOptions) { let result; typeAcquisitionDeclarations.forEach((option) => { const propertyValue = protocolOptions[option.name]; - if (propertyValue === void 0) - return; + if (propertyValue === void 0) return; (result || (result = {}))[option.name] = propertyValue; }); return result; @@ -184455,66 +184688,117 @@ function findProjectByName(projectName, projects) { } } var noopConfigFileWatcher = { close: noop }; +function getConfigFileNameFromCache(info, cache) { + if (!cache || isAncestorConfigFileInfo(info)) return void 0; + return cache.get(info.path); +} function isOpenScriptInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.containingProjects; } function isAncestorConfigFileInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.configFileInfo; } -var ProjectReferenceProjectLoadKind = /* @__PURE__ */ ((ProjectReferenceProjectLoadKind2) => { - ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["Find"] = 0] = "Find"; - ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreate"] = 1] = "FindCreate"; - ProjectReferenceProjectLoadKind2[ProjectReferenceProjectLoadKind2["FindCreateLoad"] = 2] = "FindCreateLoad"; - return ProjectReferenceProjectLoadKind2; -})(ProjectReferenceProjectLoadKind || {}); -function forEachResolvedProjectReferenceProject(project, fileName, cb, projectReferenceProjectLoadKind, reason) { +var ConfiguredProjectLoadKind = /* @__PURE__ */ ((ConfiguredProjectLoadKind2) => { + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Find"] = 0] = "Find"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Create"] = 1] = "Create"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Reload"] = 2] = "Reload"; + return ConfiguredProjectLoadKind2; +})(ConfiguredProjectLoadKind || {}); +function forEachAncestorProject(info, project, cb, kind, reason, allowDeferredClosed, reloadedProjects, delayReloadedConfiguredProjects) { + while (true) { + if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching)) return; + const configFileName = project.projectService.getConfigFileNameForFile({ + fileName: project.getConfigFilePath(), + path: info.path, + configFileInfo: true + }, kind === 0 /* Find */); + if (!configFileName) return; + const ancestor = project.projectService.findCreateOrReloadConfiguredProject( + configFileName, + kind, + reason, + allowDeferredClosed, + /*triggerFile*/ + void 0, + reloadedProjects, + /*delayLoad*/ + true, + delayReloadedConfiguredProjects + ); + if (!ancestor) return; + if (ancestor.project.isInitialLoadPending() && project.getCompilerOptions().composite) { + ancestor.project.setPotentialProjectReference(project.canonicalConfigFilePath); + } + const result = cb(ancestor.project); + if (result) return result; + project = ancestor.project; + } +} +function forEachResolvedProjectReferenceProject(project, fileName, cb, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects) { var _a; const resolvedRefs = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); - if (!resolvedRefs) - return void 0; - let seenResolvedRefs; + if (!resolvedRefs) return void 0; const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : void 0; if (possibleDefaultRef) { const configFileName = toNormalizedPath(possibleDefaultRef.sourceFile.fileName); - const child = project.projectService.findConfiguredProjectByProjectName(configFileName); + const child = project.projectService.findConfiguredProjectByProjectName( + configFileName, + allowDeferredClosed + ); if (child) { - const result = cb(child); - if (result) - return result; - } else if (projectReferenceProjectLoadKind !== 0 /* Find */) { - seenResolvedRefs = /* @__PURE__ */ new Map(); + const result = callbackWithProjectFoundUsingFind(child); + if (result) return result; + } else if (kind !== 0 /* Find */) { const result = forEachResolvedProjectReferenceProjectWorker( resolvedRefs, project.getCompilerOptions(), (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0, - projectReferenceProjectLoadKind, - project.projectService, - seenResolvedRefs + kind, + project.projectService ); - if (result) - return result; - seenResolvedRefs.clear(); + if (result) return result; } } return forEachResolvedProjectReferenceProjectWorker( resolvedRefs, project.getCompilerOptions(), (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0, - projectReferenceProjectLoadKind, - project.projectService, - seenResolvedRefs + kind, + project.projectService ); function callback(ref, loadKind) { - const configFileName = toNormalizedPath(ref.sourceFile.fileName); - const child = project.projectService.findConfiguredProjectByProjectName(configFileName) || (loadKind === 0 /* Find */ ? void 0 : loadKind === 1 /* FindCreate */ ? project.projectService.createConfiguredProject(configFileName) : loadKind === 2 /* FindCreateLoad */ ? project.projectService.createAndLoadConfiguredProject(configFileName, reason) : Debug.assertNever(loadKind)); - return child && cb(child); + const result = project.projectService.findCreateOrReloadConfiguredProject( + toNormalizedPath(ref.sourceFile.fileName), + loadKind, + reason, + allowDeferredClosed, + triggerFile, + reloadedProjects + ); + return result && (loadKind === kind ? cb(result.project, result.sentConfigFileDiag) : callbackWithProjectFoundUsingFind(result.project)); + } + function callbackWithProjectFoundUsingFind(child) { + let sentConfigFileDiag = false; + switch (kind) { + case 1 /* Create */: + sentConfigFileDiag = updateConfiguredProject(child, triggerFile); + break; + case 2 /* Reload */: + sentConfigFileDiag = child.projectService.reloadConfiguredProjectClearingSemanticCache(child, reason, reloadedProjects); + break; + case 0 /* Find */: + break; + default: + Debug.assertNever(kind); + } + const result = cb(child, sentConfigFileDiag); + if (result) return result; } } -function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, projectReferenceProjectLoadKind, projectService, seenResolvedRefs) { - const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : projectReferenceProjectLoadKind; +function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, kind, projectService, seenResolvedRefs) { + const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : kind; return forEach(resolvedProjectReferences, (ref) => { - if (!ref) - return void 0; + if (!ref) return void 0; const configFileName = toNormalizedPath(ref.sourceFile.fileName); const canonicalPath = projectService.toCanonicalFileName(configFileName); const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(canonicalPath); @@ -184553,17 +184837,41 @@ function getDetailWatchInfo(watchType, project) { function isScriptInfoWatchedFromNodeModules(info) { return !info.isScriptOpen() && info.mTime !== void 0; } -function projectContainsInfoDirectly(project, info) { - return project.containsScriptInfo(info) && !project.isSourceOfProjectReferenceRedirect(info.path); -} function updateProjectIfDirty(project) { project.invalidateResolutionsOfFailedLookupLocations(); return project.dirty && !project.updateGraph(); } -function updateConfiguredProjectWithoutConfigDiagIfDirty(project) { - project.skipConfigDiagEvent = true; - updateProjectIfDirty(project); - project.skipConfigDiagEvent = void 0; +function updateWithTriggerFile(project, triggerFile, isReload) { + if (!isReload) { + project.invalidateResolutionsOfFailedLookupLocations(); + if (!project.dirty) return false; + } + project.triggerFileForConfigFileDiag = triggerFile; + const updateLevel = project.pendingUpdateLevel; + project.updateGraph(); + if (!project.triggerFileForConfigFileDiag && !isReload) return updateLevel === 2 /* Full */; + const sent = project.projectService.sendConfigFileDiagEvent(project, triggerFile, isReload); + project.triggerFileForConfigFileDiag = void 0; + return sent; +} +function updateConfiguredProject(project, triggerFile) { + if (triggerFile) { + if (updateWithTriggerFile( + project, + triggerFile, + /*isReload*/ + false + )) return true; + } else { + updateProjectIfDirty(project); + } + return false; +} +function fileOpenReason(info) { + return `Creating possible configured project for ${info.fileName} to open`; +} +function reloadReason(reason) { + return `User requested reload projects: ${reason}`; } function setProjectOptionsUsed(project) { if (isConfiguredProject(project)) { @@ -184578,8 +184886,7 @@ function getHostWatcherMap() { return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() }; } function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { - if (!canUseWatchEvents || !service.eventHandler || !service.session) - return void 0; + if (!canUseWatchEvents || !service.eventHandler || !service.session) return void 0; const watchedFiles = getHostWatcherMap(); const watchedDirectories = getHostWatcherMap(); const watchedDirectoriesRecursive = getHostWatcherMap(); @@ -184622,8 +184929,7 @@ function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { function getOrCreateFileWatcher({ pathToId, idToCallbacks }, path, callback, event) { const key = service.toPath(path); let id = pathToId.get(key); - if (!id) - pathToId.set(key, id = ids++); + if (!id) pathToId.set(key, id = ids++); let callbacks = idToCallbacks.get(id); if (!callbacks) { idToCallbacks.set(id, callbacks = /* @__PURE__ */ new Set()); @@ -184633,10 +184939,8 @@ function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { return { close() { const callbacks2 = idToCallbacks.get(id); - if (!(callbacks2 == null ? void 0 : callbacks2.delete(callback))) - return; - if (callbacks2.size) - return; + if (!(callbacks2 == null ? void 0 : callbacks2.delete(callback))) return; + if (callbacks2.size) return; idToCallbacks.delete(id); pathToId.delete(key); service.eventHandler({ eventName: CloseFileWatcherEvent, data: { id } }); @@ -184644,10 +184948,8 @@ function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { }; } function onWatchChange(args) { - if (isArray(args)) - args.forEach(onWatchChangeRequestArgs); - else - onWatchChangeRequestArgs(args); + if (isArray(args)) args.forEach(onWatchChangeRequestArgs); + else onWatchChangeRequestArgs(args); } function onWatchChangeRequestArgs({ id, created, deleted, updated }) { onWatchEventType(id, created, 0 /* Created */); @@ -184655,8 +184957,7 @@ function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { onWatchEventType(id, updated, 1 /* Changed */); } function onWatchEventType(id, paths, eventKind) { - if (!(paths == null ? void 0 : paths.length)) - return; + if (!(paths == null ? void 0 : paths.length)) return; forEachCallback(watchedFiles, id, paths, (callback, eventPath) => callback(eventPath, eventKind)); forEachCallback(watchedDirectories, id, paths, (callback, eventPath) => callback(eventPath)); forEachCallback(watchedDirectoriesRecursive, id, paths, (callback, eventPath) => callback(eventPath)); @@ -184711,8 +185012,10 @@ var _ProjectService = class _ProjectService { * Open files: with value being project root path, and key being Path of the file that is open */ this.openFiles = /* @__PURE__ */ new Map(); - /** @internal */ + /** Config files looked up and cached config files for open script info */ this.configFileForOpenFiles = /* @__PURE__ */ new Map(); + /** Set of open script infos that are root of inferred project */ + this.rootOfInferredProjects = /* @__PURE__ */ new Set(); /** * Map of open files that are opened without complete path but have projectRoot as current directory */ @@ -184899,8 +185202,7 @@ var _ProjectService = class _ProjectService { } /** @internal */ delayEnsureProjectForOpenFiles() { - if (!this.openFiles.size) - return; + if (!this.openFiles.size) return; this.pendingEnsureProjectForOpenFiles = true; this.throttledOperations.schedule( ensureProjectForOpenFileSchedule, @@ -184919,11 +185221,9 @@ var _ProjectService = class _ProjectService { ); } delayUpdateProjectGraph(project) { - if (isProjectDeferredClose(project)) - return; + if (isProjectDeferredClose(project)) return; project.markAsDirty(); - if (isBackgroundProject(project)) - return; + if (isBackgroundProject(project)) return; const projectName = project.getProjectName(); this.pendingProjectUpdates.set(projectName, project); this.throttledOperations.schedule( @@ -185003,8 +185303,7 @@ var _ProjectService = class _ProjectService { delayUpdateProjectGraphs(projects, clearSourceMapperCache) { if (projects.length) { for (const project of projects) { - if (clearSourceMapperCache) - project.clearSourceMapperCache(); + if (clearSourceMapperCache) project.clearSourceMapperCache(); this.delayUpdateProjectGraph(project); } this.delayEnsureProjectForOpenFiles(); @@ -185070,9 +185369,28 @@ var _ProjectService = class _ProjectService { const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : void 0; } + /** + * If there is default project calculation pending for this file, + * then it completes that calculation so that correct default project is used for the project + */ + tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) { + var _a; + const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; + if (!scriptInfo) return void 0; + if ((_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(scriptInfo.path)) { + this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( + scriptInfo, + 1 /* Create */ + ); + if (scriptInfo.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(scriptInfo, this.openFiles.get(scriptInfo.path)); + } + } + return this.tryGetDefaultProjectForFile(scriptInfo); + } /** @internal */ ensureDefaultProjectForFile(fileNameOrScriptInfo) { - return this.tryGetDefaultProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); + return this.tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); } doEnsureDefaultProjectForFile(fileNameOrScriptInfo) { this.ensureProjectStructuresUptoDate(); @@ -185126,8 +185444,7 @@ var _ProjectService = class _ProjectService { true ); } else { - if (info.deferredDelete) - info.deferredDelete = void 0; + if (info.deferredDelete) info.deferredDelete = void 0; info.delayReloadNonMixedContentFile(); this.delayUpdateProjectGraphs( info.containingProjects, @@ -185213,17 +185530,13 @@ var _ProjectService = class _ProjectService { writeLog: (s) => this.logger.info(s), toPath: (s) => this.toPath(s), getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0 - })) - return; - if (config.updateLevel !== 2 /* Full */) - config.updateLevel = 1 /* RootNamesAndUpdate */; + })) return; + if (config.updateLevel !== 2 /* Full */) config.updateLevel = 1 /* RootNamesAndUpdate */; config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { var _a; - if (!watchWildcardDirectories) - return; + if (!watchWildcardDirectories) return; const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) - return; + if (!project) return; if (configuredProjectForConfig !== project && this.getHostPreferences().includeCompletionsForModuleExports) { const path = this.toPath(configFileName); if (find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { @@ -185231,8 +185544,7 @@ var _ProjectService = class _ProjectService { } } const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; - if (project.pendingUpdateLevel !== void 0 && project.pendingUpdateLevel > updateLevel) - return; + if (project.pendingUpdateLevel > updateLevel) return; if (this.openFiles.has(fileOrDirectoryPath)) { const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); if (info.isAttached(project)) { @@ -185273,19 +185585,16 @@ var _ProjectService = class _ProjectService { /** @internal */ delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, loadReason) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) - return false; + if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) return false; let scheduledAnyProjectUpdate = false; configFileExistenceInfo.config.updateLevel = 2 /* Full */; configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => { var _a; const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) - return; + if (!project) return; scheduledAnyProjectUpdate = true; if (projectCanonicalPath === canonicalConfigFilePath) { - if (project.isInitialLoadPending()) - return; + if (project.isInitialLoadPending()) return; project.pendingUpdateLevel = 2 /* Full */; project.pendingUpdateReason = loadReason; this.delayUpdateProjectGraph(project); @@ -185302,14 +185611,13 @@ var _ProjectService = class _ProjectService { return scheduledAnyProjectUpdate; } /** @internal */ - onConfigFileChanged(canonicalConfigFilePath, eventKind) { + onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); const project = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); const wasDefferedClose = project == null ? void 0 : project.deferredClose; if (eventKind === 2 /* Deleted */) { configFileExistenceInfo.exists = false; - if (project) - project.deferredClose = true; + if (project) project.deferredClose = true; } else { configFileExistenceInfo.exists = true; if (wasDefferedClose) { @@ -185317,44 +185625,35 @@ var _ProjectService = class _ProjectService { project.markAsDirty(); } } - this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, "Change in config file detected"); - this.delayReloadConfiguredProjectsForFile( - configFileExistenceInfo, - !wasDefferedClose && eventKind !== 2 /* Deleted */ ? identity : ( - // Reload open files if they are root of inferred project - returnTrue - ), - // Reload all the open files impacted by config file + this.delayUpdateProjectsFromParsedConfigOnConfigFileChange( + canonicalConfigFilePath, "Change in config file detected" ); - this.delayEnsureProjectForOpenFiles(); - } - /** - * This function goes through all the openFiles and tries to file the config file for them. - * If the config file is found and it refers to existing project, it schedules the reload it for reload - * If there is no existing project it just opens the configured project for the config file - * shouldReloadProjectFor provides a way to filter out files to reload configured project for - */ - delayReloadConfiguredProjectsForFile(configFileExistenceInfo, shouldReloadProjectFor, reason) { - var _a; - const updatedProjects = /* @__PURE__ */ new Set(); - (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.forEach((infoIsRootOfInferredProject, path) => { + const updatedProjects = new Set(project ? [project] : void 0); + this.openFiles.forEach((_projectRootPath, path) => { + var _a, _b; + const configFileForOpenFile = this.configFileForOpenFiles.get(path); + if (!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(path))) return; this.configFileForOpenFiles.delete(path); - if (!shouldReloadProjectFor(infoIsRootOfInferredProject)) { - return; - } const info = this.getScriptInfoForPath(path); - Debug.assert(info.isScriptOpen()); - const configFileName = this.getConfigFileNameForFile(info); - if (configFileName) { - const project = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); - if (tryAddToSet(updatedProjects, project)) { - project.pendingUpdateLevel = 2 /* Full */; - project.pendingUpdateReason = reason; - this.delayUpdateProjectGraph(project); - } + const newConfigFileNameForInfo = this.getConfigFileNameForFile( + info, + /*findFromCacheOnly*/ + false + ); + if (!newConfigFileNameForInfo) return; + const projectForInfo = this.findConfiguredProjectByProjectName(newConfigFileNameForInfo) ?? this.createConfiguredProject( + newConfigFileNameForInfo, + `Change in config file ${configFileName} detected, ${fileOpenReason(info)}` + ); + if (!((_b = this.pendingOpenFileProjectUpdates) == null ? void 0 : _b.has(path))) { + (this.pendingOpenFileProjectUpdates ?? (this.pendingOpenFileProjectUpdates = /* @__PURE__ */ new Map())).set(path, configFileForOpenFile); + } + if (tryAddToSet(updatedProjects, projectForInfo) && projectForInfo.isInitialLoadPending()) { + this.delayUpdateProjectGraph(projectForInfo); } }); + this.delayEnsureProjectForOpenFiles(); } removeProject(project) { this.logger.info("`remove Project::"); @@ -185455,9 +185754,10 @@ var _ProjectService = class _ProjectService { * @param info The file that has been closed or newly configured */ closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) { + var _a; const fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName); info.close(fileExists); - this.stopWatchingConfigFilesForClosedScriptInfo(info); + this.stopWatchingConfigFilesForScriptInfo(info); const canonicalFileName = this.toCanonicalFileName(info.fileName); if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); @@ -185471,7 +185771,7 @@ var _ProjectService = class _ProjectService { const updateLevel = p.openFileWatchTriggered.get(info.path); if (updateLevel !== void 0) { p.openFileWatchTriggered.delete(info.path); - if (p.pendingUpdateLevel !== void 0 && p.pendingUpdateLevel < updateLevel) { + if (p.pendingUpdateLevel < updateLevel) { p.pendingUpdateLevel = updateLevel; p.markFileAsDirty(info.path); } @@ -185493,6 +185793,8 @@ var _ProjectService = class _ProjectService { } this.openFiles.delete(info.path); this.configFileForOpenFiles.delete(info.path); + (_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(info.path); + Debug.assert(!this.rootOfInferredProjects.has(info)); if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) { this.assignOrphanScriptInfosToInferredProject(); } @@ -185519,21 +185821,15 @@ var _ProjectService = class _ProjectService { info.closeSourceMapFileWatcher(); } configFileExists(configFileName, canonicalConfigFilePath, info) { - var _a; - let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (configFileExistenceInfo) { - if (isOpenScriptInfo(info) && !((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) { - (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false); - } - return configFileExistenceInfo.exists; - } - const exists = this.host.fileExists(configFileName); + const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); let openFilesImpactedByConfigFile; - if (isOpenScriptInfo(info)) { - (openFilesImpactedByConfigFile || (openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, false); + if (this.openFiles.has(info.path) && !isAncestorConfigFileInfo(info)) { + if (configFileExistenceInfo) (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path); + else (openFilesImpactedByConfigFile = /* @__PURE__ */ new Set()).add(info.path); } - configFileExistenceInfo = { exists, openFilesImpactedByConfigFile }; - this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + if (configFileExistenceInfo) return configFileExistenceInfo.exists; + const exists = this.host.fileExists(configFileName); + this.configFileExistenceInfoCache.set(canonicalConfigFilePath, { exists, openFilesImpactedByConfigFile }); return exists; } /** @internal */ @@ -185543,7 +185839,7 @@ var _ProjectService = class _ProjectService { if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { configFileExistenceInfo.watcher = this.watchFactory.watchFile( configFileName, - (_fileName, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + (_fileName, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind), 2e3 /* High */, this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions, getDirectoryPath(configFileName)), WatchType.ConfigFile, @@ -185553,25 +185849,17 @@ var _ProjectService = class _ProjectService { const projects = configFileExistenceInfo.config.projects; projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); } - /** - * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project - */ - configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo) { - return configFileExistenceInfo.openFilesImpactedByConfigFile && forEachEntry(configFileExistenceInfo.openFilesImpactedByConfigFile, identity); - } /** @internal */ releaseParsedConfig(canonicalConfigFilePath, forProject) { var _a, _b, _c; const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) - return; - if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size) - return; + if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) return; + if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size) return; configFileExistenceInfo.config = void 0; clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); Debug.checkDefined(configFileExistenceInfo.watcher); if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) { - if (this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { + if (configFileExistenceInfo.inferredProjectRoots) { if (!canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath)))) { configFileExistenceInfo.watcher.close(); configFileExistenceInfo.watcher = noopConfigFileWatcher; @@ -185586,36 +185874,35 @@ var _ProjectService = class _ProjectService { } } /** - * Close the config file watcher in the cached ConfigFileExistenceInfo - * if there arent any open files that are root of inferred project and there is no parsed config held by any project - * + * This is called on file close or when its removed from inferred project as root, + * so that we handle the watches and inferred project root data * @internal */ - closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo) { - if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !this.configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo)) { - configFileExistenceInfo.watcher.close(); - configFileExistenceInfo.watcher = void 0; - } - } - /** - * This is called on file close, so that we stop watching the config file for this script info - */ - stopWatchingConfigFilesForClosedScriptInfo(info) { - Debug.assert(!info.isScriptOpen()); + stopWatchingConfigFilesForScriptInfo(info) { + if (this.serverMode !== 0 /* Semantic */) return; + const isRootOfInferredProject = this.rootOfInferredProjects.delete(info); + const isOpen = info.isScriptOpen(); + if (isOpen && !isRootOfInferredProject) return; this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { var _a, _b, _c; const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (configFileExistenceInfo) { - const infoIsRootOfInferredProject = (_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.get(info.path); - (_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path); - if (infoIsRootOfInferredProject) { - this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); - } - if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) { - Debug.assert(!configFileExistenceInfo.watcher); - this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + if (!configFileExistenceInfo) return; + if (isOpen) { + if (!((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) return; + } else { + if (!((_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path))) return; + } + if (isRootOfInferredProject) { + configFileExistenceInfo.inferredProjectRoots--; + if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !configFileExistenceInfo.inferredProjectRoots) { + configFileExistenceInfo.watcher.close(); + configFileExistenceInfo.watcher = void 0; } } + if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) { + Debug.assert(!configFileExistenceInfo.watcher); + this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); + } }); } /** @@ -185624,39 +185911,27 @@ var _ProjectService = class _ProjectService { * @internal */ startWatchingConfigFilesForInferredProjectRoot(info) { + if (this.serverMode !== 0 /* Semantic */) return; Debug.assert(info.isScriptOpen()); + this.rootOfInferredProjects.add(info); this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => { let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { - configFileExistenceInfo = { exists: this.host.fileExists(configFileName) }; + configFileExistenceInfo = { exists: this.host.fileExists(configFileName), inferredProjectRoots: 1 }; this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); + } else { + configFileExistenceInfo.inferredProjectRoots = (configFileExistenceInfo.inferredProjectRoots ?? 0) + 1; } - (configFileExistenceInfo.openFilesImpactedByConfigFile || (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Map())).set(info.path, true); + (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path); configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile( configFileName, - (_filename, eventKind) => this.onConfigFileChanged(canonicalConfigFilePath, eventKind), + (_filename, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind), 2e3 /* High */, this.hostConfiguration.watchOptions, WatchType.ConfigFileForInferredRoot ) : noopConfigFileWatcher); }); } - /** - * This is called by inferred project whenever root script info is removed from it - * - * @internal - */ - stopWatchingConfigFilesForInferredProjectRoot(info) { - this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { - var _a; - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path)) { - Debug.assert(info.isScriptOpen()); - configFileExistenceInfo.openFilesImpactedByConfigFile.set(info.path, false); - this.closeConfigFileWatcherOnReleaseOfOpenFile(configFileExistenceInfo); - } - }); - } /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -185672,8 +185947,7 @@ var _ProjectService = class _ProjectService { Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); const projectRootPath = this.openFiles.get(info.path); const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path)); - if (scriptInfo.isDynamic) - return void 0; + if (scriptInfo.isDynamic) return void 0; let searchPath = asNormalizedPath(getDirectoryPath(info.fileName)); const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames); const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); @@ -185683,19 +185957,16 @@ var _ProjectService = class _ProjectService { const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json")); let result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); - if (result) - return tsconfigFileName; + if (result) return tsconfigFileName; const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json")); result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); - if (result) - return jsconfigFileName; + if (result) return jsconfigFileName; if (isNodeModulesDirectory(canonicalSearchPath)) { break; } } const parentPath = asNormalizedPath(getDirectoryPath(searchPath)); - if (parentPath === searchPath) - break; + if (parentPath === searchPath) break; searchPath = parentPath; searchInDirectory = true; } while (anySearchPathOk || isSearchPathInProjectRoot()); @@ -185703,11 +185974,25 @@ var _ProjectService = class _ProjectService { } /** @internal */ findDefaultConfiguredProject(info) { - if (!info.isScriptOpen()) - return void 0; - const configFileName = this.getConfigFileNameForFile(info); - const project = configFileName && this.findConfiguredProjectByProjectName(configFileName); - return project && projectContainsInfoDirectly(project, info) ? project : project == null ? void 0 : project.getDefaultChildProjectFromProjectWithReferences(info); + var _a; + return info.isScriptOpen() ? (_a = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( + info, + 0 /* Find */ + )) == null ? void 0 : _a.defaultProject : void 0; + } + /** Get cached configFileName for scriptInfo or ancestor of open script info */ + getConfigFileNameForFileFromCache(info, lookInPendingFilesForValue) { + if (lookInPendingFilesForValue) { + const result = getConfigFileNameFromCache(info, this.pendingOpenFileProjectUpdates); + if (result !== void 0) return result; + } + return getConfigFileNameFromCache(info, this.configFileForOpenFiles); + } + /** Caches the configFilename for script info or ancestor of open script info */ + setConfigFileNameForFileInCache(info, configFileName) { + if (!this.openFiles.has(info.path)) return; + if (isAncestorConfigFileInfo(info)) return; + this.configFileForOpenFiles.set(info.path, configFileName || false); } /** * This function tries to search for a tsconfig.json for the given file. @@ -185718,18 +186003,16 @@ var _ProjectService = class _ProjectService { * the newly opened file. * If script info is passed in, it is asserted to be open script info * otherwise just file name + * when findFromCacheOnly is true only looked up in cache instead of hitting disk to figure things out + * @internal */ - getConfigFileNameForFile(info) { - if (!isAncestorConfigFileInfo(info)) { - const result = this.configFileForOpenFiles.get(info.path); - if (result !== void 0) - return result || void 0; - } + getConfigFileNameForFile(info, findFromCacheOnly) { + const fromCache = this.getConfigFileNameForFileFromCache(info, findFromCacheOnly); + if (fromCache !== void 0) return fromCache || void 0; + if (findFromCacheOnly) return void 0; const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info)); this.logger.info(`getConfigFileNameForFile:: File: ${info.fileName} ProjectRootPath: ${this.openFiles.get(info.path)}:: Result: ${configFileName}`); - if (isOpenScriptInfo(info)) { - this.configFileForOpenFiles.set(info.path, configFileName || false); - } + this.setConfigFileNameForFileInCache(info, configFileName); return configFileName; } printProjects() { @@ -185749,10 +186032,10 @@ var _ProjectService = class _ProjectService { this.logger.endGroup(); } /** @internal */ - findConfiguredProjectByProjectName(configFileName) { + findConfiguredProjectByProjectName(configFileName, allowDeferredClosed) { const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); const result = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); - return !(result == null ? void 0 : result.deferredClose) ? result : void 0; + return allowDeferredClosed ? result : !(result == null ? void 0 : result.deferredClose) ? result : void 0; } getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) { return this.configuredProjects.get(canonicalConfigFilePath); @@ -185786,7 +186069,7 @@ var _ProjectService = class _ProjectService { createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) { const compilerOptions = convertCompilerOptions(options); const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName))); - const project = new ExternalProject2( + const project = new ExternalProject( projectFileName, this, this.documentRegistry, @@ -185832,7 +186115,7 @@ var _ProjectService = class _ProjectService { exclude: projectOptions && projectOptions.configHasExcludeProperty, compileOnSave: project.compileOnSaveEnabled, configFileName: configFileName(), - projectType: project instanceof ExternalProject2 ? "external" : "configured", + projectType: project instanceof ExternalProject ? "external" : "configured", languageServiceEnabled: project.languageServiceEnabled, version }; @@ -185857,7 +186140,7 @@ var _ProjectService = class _ProjectService { project.markAsDirty(); } /** @internal */ - createConfiguredProject(configFileName) { + createConfiguredProject(configFileName, reason) { var _a; (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); this.logger.info(`Creating configuration project ${configFileName}`); @@ -185880,33 +186163,14 @@ var _ProjectService = class _ProjectService { canonicalConfigFilePath, this, this.documentRegistry, - configFileExistenceInfo.config.cachedDirectoryStructureHost + configFileExistenceInfo.config.cachedDirectoryStructureHost, + reason ); Debug.assert(!this.configuredProjects.has(canonicalConfigFilePath)); this.configuredProjects.set(canonicalConfigFilePath, project); this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); return project; } - /** @internal */ - createConfiguredProjectWithDelayLoad(configFileName, reason) { - const project = this.createConfiguredProject(configFileName); - project.pendingUpdateLevel = 2 /* Full */; - project.pendingUpdateReason = reason; - return project; - } - /** @internal */ - createAndLoadConfiguredProject(configFileName, reason) { - const project = this.createConfiguredProject(configFileName); - this.loadConfiguredProject(project, reason); - return project; - } - /** @internal */ - createLoadAndUpdateConfiguredProject(configFileName, reason) { - const project = this.createAndLoadConfiguredProject(configFileName, reason); - project.skipConfigDiagEvent = true; - project.updateGraph(); - return project; - } /** * Read the config file of the project, and update the project root file names. * @@ -185956,8 +186220,7 @@ var _ProjectService = class _ProjectService { ensureParsedConfigUptoDate(configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) { var _a, _b, _c; if (configFileExistenceInfo.config) { - if (!configFileExistenceInfo.config.updateLevel) - return configFileExistenceInfo; + if (!configFileExistenceInfo.config.updateLevel) return configFileExistenceInfo; if (configFileExistenceInfo.config.updateLevel === 1 /* RootNamesAndUpdate */) { this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); return configFileExistenceInfo; @@ -185967,8 +186230,7 @@ var _ProjectService = class _ProjectService { const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName)); const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : ""); const configFileErrors = configFile.parseDiagnostics; - if (!isString(configFileContent)) - configFileErrors.push(configFileContent); + if (!isString(configFileContent)) configFileErrors.push(configFileContent); const configDir = getDirectoryPath(configFilename); const parsedCommandLine = parseJsonSourceFileConfigFileContent( configFile, @@ -186031,8 +186293,7 @@ var _ProjectService = class _ProjectService { (_a2 = this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((canonicalPath) => { ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; }); - if (ensureProjectsForOpenFiles) - this.delayEnsureProjectForOpenFiles(); + if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); }, 2e3 /* High */, this.hostConfiguration.watchOptions, @@ -186047,8 +186308,7 @@ var _ProjectService = class _ProjectService { watchWildcards(configFileName, { exists, config }, forProject) { config.projects.set(forProject.canonicalConfigFilePath, true); if (exists) { - if (config.watchedDirectories && !config.watchedDirectoriesStale) - return; + if (config.watchedDirectories && !config.watchedDirectoriesStale) return; config.watchedDirectoriesStale = false; updateWatchingWildcardDirectories( config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */ new Map()), @@ -186058,8 +186318,7 @@ var _ProjectService = class _ProjectService { ); } else { config.watchedDirectoriesStale = false; - if (!config.watchedDirectories) - return; + if (!config.watchedDirectories) return; clearMap(config.watchedDirectories, closeFileWatcherOf); config.watchedDirectories = void 0; } @@ -186071,8 +186330,7 @@ var _ProjectService = class _ProjectService { return; } configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); - if (forEachEntry(configFileExistenceInfo.config.projects, identity)) - return; + if (forEachEntry(configFileExistenceInfo.config.projects, identity)) return; if (configFileExistenceInfo.config.watchedDirectories) { clearMap(configFileExistenceInfo.config.watchedDirectories, closeFileWatcherOf); configFileExistenceInfo.config.watchedDirectories = void 0; @@ -186080,6 +186338,7 @@ var _ProjectService = class _ProjectService { configFileExistenceInfo.config.watchedDirectoriesStale = void 0; } updateNonInferredProjectFiles(project, files, propertyReader) { + var _a; const projectRootFilesMap = project.getRootFilesMap(); const newRootScriptInfoMap = /* @__PURE__ */ new Map(); for (const f of files) { @@ -186091,7 +186350,7 @@ var _ProjectService = class _ProjectService { path = normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName); const existingValue = projectRootFilesMap.get(path); if (existingValue) { - if (existingValue.info) { + if (((_a = existingValue.info) == null ? void 0 : _a.path) === path) { project.removeFile( existingValue.info, /*fileExists*/ @@ -186169,8 +186428,7 @@ var _ProjectService = class _ProjectService { } /** @internal */ reloadFileNamesOfParsedConfig(configFileName, config) { - if (config.updateLevel === void 0) - return config.parsedCommandLine.fileNames; + if (config.updateLevel === void 0) return config.parsedCommandLine.fileNames; Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */); const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; const fileNames = getFileNamesFromConfigSpecs( @@ -186187,25 +186445,35 @@ var _ProjectService = class _ProjectService { setFileNamesOfAutpImportProviderOrAuxillaryProject(project, fileNames) { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); } + /** @internal */ + reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects) { + if (!tryAddToSet(reloadedProjects, project)) return false; + this.clearSemanticCache(project); + this.reloadConfiguredProject(project, reloadReason(reason)); + return true; + } /** * Read the config file of the project again by clearing the cache and update the project graph * * @internal */ - reloadConfiguredProject(project, reason, isInitialLoad, clearSemanticCache) { + reloadConfiguredProject(project, reason) { + project.isInitialLoadPending = returnFalse; + project.pendingUpdateReason = void 0; + project.pendingUpdateLevel = 0 /* Update */; const host = project.getCachedDirectoryStructureHost(); - if (clearSemanticCache) - this.clearSemanticCache(project); host.clearCache(); - const configFileName = project.getConfigFilePath(); - this.logger.info(`${isInitialLoad ? "Loading" : "Reloading"} configured project ${configFileName}`); this.loadConfiguredProject(project, reason); - project.skipConfigDiagEvent = true; - project.updateGraph(); - this.sendConfigFileDiagEvent(project, configFileName); + updateWithTriggerFile( + project, + project.triggerFileForConfigFileDiag ?? project.getConfigFilePath(), + /*isReload*/ + true + ); } /** @internal */ clearSemanticCache(project) { + project.originalConfiguredProjects = void 0; project.resolutionCache.clear(); project.getLanguageService( /*ensureSynchronized*/ @@ -186215,21 +186483,19 @@ var _ProjectService = class _ProjectService { project.markAsDirty(); } /** @internal */ - sendConfigFileDiagEvent(project, triggerFile) { - if (!this.eventHandler || this.suppressDiagnosticEvents) { - return; - } + sendConfigFileDiagEvent(project, triggerFile, force) { + if (!this.eventHandler || this.suppressDiagnosticEvents) return false; const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); diagnostics.push(...project.getAllProjectErrors()); - if (!triggerFile && !!diagnostics.length === !!project.hasConfigFileDiagnostics) - return; - project.hasConfigFileDiagnostics = !!diagnostics.length; + if (!force && diagnostics.length === (project.configDiagDiagnosticsReported ?? 0)) return false; + project.configDiagDiagnosticsReported = diagnostics.length; this.eventHandler( { eventName: ConfigFileDiagEvent, data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile: triggerFile ?? project.getConfigFilePath() } } ); + return true; } getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) { if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root @@ -186252,12 +186518,9 @@ var _ProjectService = class _ProjectService { } let bestMatch; for (const project of this.inferredProjects) { - if (!project.projectRootPath) - continue; - if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) - continue; - if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) - continue; + if (!project.projectRootPath) continue; + if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue; + if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue; bestMatch = project; } return bestMatch; @@ -186329,8 +186592,7 @@ var _ProjectService = class _ProjectService { getScriptInfoOrConfig(uncheckedFileName) { const path = toNormalizedPath(uncheckedFileName); const info = this.getScriptInfoForNormalizedPath(path); - if (info) - return info; + if (info) return info; const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); return configProject && configProject.getCompilerOptions().configFile; } @@ -186401,8 +186663,7 @@ All files are: ${JSON.stringify(names)}`, "Err" /* Err */); (fileOrDirectory) => { var _a; const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory)); - if (!fileOrDirectoryPath) - return; + if (!fileOrDirectoryPath) return; const basename = getBaseFileName(fileOrDirectoryPath); if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename === "package.json" || basename === "node_modules")) { result.affectedModuleSpecifierCacheProjects.forEach((project) => { @@ -186621,11 +186882,9 @@ Dynamic files must always be opened with service's current directory or service true ); sourceMapFileInfo = mapInfo || mapFileNameFromDts; - if (!mapInfo || mapInfo.deferredDelete) - return void 0; + if (!mapInfo || mapInfo.deferredDelete) return void 0; const snap = mapInfo.getSnapshot(); - if (mapInfo.documentPositionMapper !== void 0) - return mapInfo.documentPositionMapper; + if (mapInfo.documentPositionMapper !== void 0) return mapInfo.documentPositionMapper; return getSnapshotText(snap); }; const projectName = project.projectName; @@ -186640,8 +186899,7 @@ Dynamic files must always be opened with service's current directory or service if (!isString(sourceMapFileInfo)) { declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; sourceMapFileInfo.declarationInfoPath = declarationInfo.path; - if (!sourceMapFileInfo.deferredDelete) - sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; + if (!sourceMapFileInfo.deferredDelete) sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); } else { declarationInfo.sourceMapFilePath = { @@ -186697,8 +186955,7 @@ Dynamic files must always be opened with service's current directory or service if (project) { const path = project.toPath(fileName); const sourceFile = project.getSourceFile(path); - if (sourceFile && sourceFile.resolvedPath === path) - return sourceFile; + if (sourceFile && sourceFile.resolvedPath === path) return sourceFile; } const info = this.getOrCreateScriptInfoNotOpenedByClient( fileName, @@ -186707,16 +186964,14 @@ Dynamic files must always be opened with service's current directory or service /*deferredDeleteOk*/ false ); - if (!info) - return void 0; + if (!info) return void 0; if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); if (sourceMapInfo) { (sourceMapInfo.sourceInfos ?? (sourceMapInfo.sourceInfos = /* @__PURE__ */ new Set())).add(info.path); } } - if (info.cacheSourceFile) - return info.cacheSourceFile.sourceFile; + if (info.cacheSourceFile) return info.cacheSourceFile.sourceFile; if (!info.sourceFileLike) { info.sourceFileLike = { get text() { @@ -186763,7 +187018,7 @@ Dynamic files must always be opened with service's current directory or service if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { this.externalProjectToConfiguredProjectMap.forEach( (projects) => projects.forEach((project) => { - if (!project.deferredClose && !project.isClosed() && project.hasExternalProjectRef() && project.pendingUpdateLevel === 2 /* Full */ && !this.pendingProjectUpdates.has(project.getProjectName())) { + if (!project.deferredClose && !project.isClosed() && project.pendingUpdateLevel === 2 /* Full */ && !this.hasPendingProjectUpdate(project)) { project.updateGraph(); } }) @@ -186811,10 +187066,8 @@ Dynamic files must always be opened with service's current directory or service reloadProjects() { this.logger.info("reload projects."); this.filenameToScriptInfo.forEach((info) => { - if (this.openFiles.has(info.path)) - return; - if (!info.fileWatcher) - return; + if (this.openFiles.has(info.path)) return; + if (!info.fileWatcher) return; this.onSourceFileChanged( info, this.host.fileExists(info.fileName) ? info.deferredDelete ? 0 /* Created */ : 1 /* Changed */ : 2 /* Deleted */ @@ -186825,80 +187078,57 @@ Dynamic files must always be opened with service's current directory or service this.pendingProjectUpdates.delete(projectName); }); this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); + this.pendingOpenFileProjectUpdates = void 0; this.pendingEnsureProjectForOpenFiles = false; this.configFileExistenceInfoCache.forEach((info) => { - if (info.config) - info.config.updateLevel = 2 /* Full */; + if (info.config) info.config.updateLevel = 2 /* Full */; }); - this.reloadConfiguredProjectForFiles("User requested reload projects"); + this.configFileForOpenFiles.clear(); this.externalProjects.forEach((project) => { this.clearSemanticCache(project); project.updateGraph(); }); - this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); - this.ensureProjectForOpenFiles(); - this.logger.info("After reloading projects.."); - this.printProjects(); - } - /** - * This function goes through all the openFiles and tries to file the config file for them. - * If the config file is found and it refers to existing project, it reloads it either immediately - * If there is no existing project it just opens the configured project for the config file - */ - reloadConfiguredProjectForFiles(reason) { - var _a; - const updatedProjects = /* @__PURE__ */ new Set(); - const reloadChildProject = (child) => { - if (tryAddToSet(updatedProjects, child)) { - this.reloadConfiguredProject( - child, - reason, - /*isInitialLoad*/ - false, - /*clearSemanticCache*/ - true - ); - } - }; - (_a = this.openFiles) == null ? void 0 : _a.forEach((_projectRoot, path) => { - this.configFileForOpenFiles.delete(path); - const info = this.getScriptInfoForPath(path); - Debug.assert(info.isScriptOpen()); - const configFileName = this.getConfigFileNameForFile(info); - if (configFileName) { - const project = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProject(configFileName); - if (tryAddToSet(updatedProjects, project)) { - this.reloadConfiguredProject( + const reloadedConfiguredProjects = /* @__PURE__ */ new Set(); + const delayReloadedConfiguredProjects = /* @__PURE__ */ new Set(); + this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => { + const reason = `Reloading configured project in external project: ${externalProjectName}`; + projects.forEach((project) => { + if (this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) { + if (!project.isInitialLoadPending()) { + this.clearSemanticCache(project); + project.pendingUpdateLevel = 2 /* Full */; + project.pendingUpdateReason = reloadReason(reason); + } + delayReloadedConfiguredProjects.add(project); + } else { + this.reloadConfiguredProjectClearingSemanticCache( project, reason, - /*isInitialLoad*/ - false, - /*clearSemanticCache*/ - true + reloadedConfiguredProjects ); - if (!projectContainsInfoDirectly(project, info)) { - const referencedProject = forEachResolvedProjectReferenceProject( - project, - info.path, - (child) => { - reloadChildProject(child); - return projectContainsInfoDirectly(child, info); - }, - 1 /* FindCreate */ - ); - if (referencedProject) { - forEachResolvedProjectReferenceProject( - project, - /*fileName*/ - void 0, - reloadChildProject, - 0 /* Find */ - ); - } - } } - } + }); + }); + this.openFiles.forEach((_projectRootPath, path) => { + const info = this.getScriptInfoForPath(path); + if (find(info.containingProjects, isExternalProject)) return; + this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( + info, + 2 /* Reload */, + reloadedConfiguredProjects, + delayReloadedConfiguredProjects + ); }); + delayReloadedConfiguredProjects.forEach((p) => reloadedConfiguredProjects.add(p)); + this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); + this.ensureProjectForOpenFiles(); + this.cleanupProjectsAndScriptInfos( + reloadedConfiguredProjects, + new Set(this.openFiles.keys()), + new Set(this.externalProjectToConfiguredProjectMap.keys()) + ); + this.logger.info("After reloading projects.."); + this.printProjects(); } /** * Remove the root of inferred project if script info is part of another project @@ -186926,6 +187156,14 @@ Dynamic files must always be opened with service's current directory or service ensureProjectForOpenFiles() { this.logger.info("Before ensureProjectForOpenFiles:"); this.printProjects(); + const pendingOpenFileProjectUpdates = this.pendingOpenFileProjectUpdates; + this.pendingOpenFileProjectUpdates = void 0; + pendingOpenFileProjectUpdates == null ? void 0 : pendingOpenFileProjectUpdates.forEach( + (_config, path) => this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( + this.getScriptInfoForPath(path), + 1 /* Create */ + ) + ); this.openFiles.forEach((projectRootPath, path) => { const info = this.getScriptInfoForPath(path); if (info.isOrphan()) { @@ -186958,16 +187196,17 @@ Dynamic files must always be opened with service's current directory or service getOriginalLocationEnsuringConfiguredProject(project, location) { const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName); const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location); - if (!originalLocation) - return void 0; + if (!originalLocation) return void 0; const { fileName } = originalLocation; const scriptInfo = this.getScriptInfo(fileName); - if (!scriptInfo && !this.host.fileExists(fileName)) - return void 0; + if (!scriptInfo && !this.host.fileExists(fileName)) return void 0; const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) }; - const configFileName = this.getConfigFileNameForFile(originalFileInfo); - if (!configFileName) - return void 0; + const configFileName = this.getConfigFileNameForFile( + originalFileInfo, + /*findFromCacheOnly*/ + false + ); + if (!configFileName) return void 0; let configuredProject = this.findConfiguredProjectByProjectName(configFileName); if (!configuredProject) { if (project.getCompilerOptions().disableReferencedProjectLoad) { @@ -186976,33 +187215,27 @@ Dynamic files must always be opened with service's current directory or service } return (scriptInfo == null ? void 0 : scriptInfo.containingProjects.length) ? originalLocation : location; } - configuredProject = this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`); + configuredProject = this.createConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`); } updateProjectIfDirty(configuredProject); const projectContainsOriginalInfo = (project2) => { const info = this.getScriptInfo(fileName); - return info && projectContainsInfoDirectly(project2, info); + return info && project2.containsScriptInfo(info) && !project2.isSourceOfProjectReferenceRedirect(info.path); }; if (configuredProject.isSolution() || !projectContainsOriginalInfo(configuredProject)) { configuredProject = forEachResolvedProjectReferenceProject( configuredProject, fileName, - (child) => { - updateProjectIfDirty(child); - return projectContainsOriginalInfo(child) ? child : void 0; - }, - 2 /* FindCreateLoad */, + (child) => projectContainsOriginalInfo(child) ? child : void 0, + 1 /* Create */, `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}` ); - if (!configuredProject) - return void 0; - if (configuredProject === project) - return originalLocation; + if (!configuredProject) return void 0; + if (configuredProject === project) return originalLocation; } addOriginalConfiguredProject(configuredProject); const originalScriptInfo = this.getScriptInfo(fileName); - if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) - return void 0; + if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) return void 0; originalScriptInfo.containingProjects.forEach((project2) => { if (isConfiguredProject(project2)) { addOriginalConfiguredProject(project2); @@ -187043,89 +187276,148 @@ Dynamic files must always be opened with service's current directory or service assignProjectToOpenedScriptInfo(info) { let configFileName; let configFileErrors; - let project = this.findExternalProjectContainingOpenScriptInfo(info); + const project = this.findExternalProjectContainingOpenScriptInfo(info); let retainProjects; - let projectForConfigFileDiag; - let defaultConfigProjectIsCreated = false; + let sentConfigDiag; if (!project && this.serverMode === 0 /* Semantic */) { - configFileName = this.getConfigFileNameForFile(info); - if (configFileName) { - project = this.findConfiguredProjectByProjectName(configFileName); - if (!project) { - project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${info.fileName} to open`); - defaultConfigProjectIsCreated = true; - } else { - updateConfiguredProjectWithoutConfigDiagIfDirty(project); - } - projectForConfigFileDiag = project.containsScriptInfo(info) ? project : void 0; - retainProjects = project; - if (!projectContainsInfoDirectly(project, info)) { - forEachResolvedProjectReferenceProject( - project, - info.path, - (child) => { - updateConfiguredProjectWithoutConfigDiagIfDirty(child); - if (!isArray(retainProjects)) { - retainProjects = [project, child]; - } else { - retainProjects.push(child); - } - if (projectContainsInfoDirectly(child, info)) { - projectForConfigFileDiag = child; - return child; - } - if (!projectForConfigFileDiag && child.containsScriptInfo(info)) { - projectForConfigFileDiag = child; - } - }, - 2 /* FindCreateLoad */, - `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open` - ); - } - if (projectForConfigFileDiag) { - configFileName = projectForConfigFileDiag.getConfigFilePath(); - if (projectForConfigFileDiag !== project || defaultConfigProjectIsCreated) { - configFileErrors = projectForConfigFileDiag.getAllProjectErrors(); - this.sendConfigFileDiagEvent(projectForConfigFileDiag, info.fileName); - } - } else { - configFileName = void 0; + const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( + info, + 1 /* Create */ + ); + if (result) { + retainProjects = result.seenProjects; + sentConfigDiag = result.sentConfigDiag; + if (result.defaultProject) { + configFileName = result.defaultProject.getConfigFilePath(); + configFileErrors = result.defaultProject.getAllProjectErrors(); } - this.createAncestorProjects(info, project); } } info.containingProjects.forEach(updateProjectIfDirty); if (info.isOrphan()) { - if (isArray(retainProjects)) { - retainProjects.forEach((project2) => this.sendConfigFileDiagEvent(project2, info.fileName)); - } else if (retainProjects) { - this.sendConfigFileDiagEvent(retainProjects, info.fileName); - } + retainProjects == null ? void 0 : retainProjects.forEach((project2) => { + if (!sentConfigDiag.has(project2)) this.sendConfigFileDiagEvent( + project2, + info.fileName, + /*force*/ + true + ); + }); Debug.assert(this.openFiles.has(info.path)); this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); } Debug.assert(!info.isOrphan()); return { configFileName, configFileErrors, retainProjects }; } - createAncestorProjects(info, project) { - if (!info.isAttached(project)) - return; - while (true) { - if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching)) - return; - const configFileName = this.getConfigFileNameForFile({ - fileName: project.getConfigFilePath(), - path: info.path, - configFileInfo: true - }); - if (!configFileName) - return; - const ancestor = this.findConfiguredProjectByProjectName(configFileName) || this.createConfiguredProjectWithDelayLoad(configFileName, `Creating project possibly referencing default composite project ${project.getProjectName()} of open file ${info.fileName}`); - if (ancestor.isInitialLoadPending()) { - ancestor.setPotentialProjectReference(project.canonicalConfigFilePath); - } - project = ancestor; + /** + * Depending on kind + * - Find the configuedProject and return it - if allowDeferredClosed is set it will find the deferredClosed project as well + * - Create - if the project doesnt exist, it creates one as well. If not delayLoad, the project is updated (with triggerFile if passed) + * - Reload - if the project doesnt exist, it creates one. If not delayLoad, the project is reloaded clearing semantic cache + * @internal + */ + findCreateOrReloadConfiguredProject(configFileName, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects, delayLoad, delayReloadedConfiguredProjects) { + let project = this.findConfiguredProjectByProjectName(configFileName, allowDeferredClosed); + let sentConfigFileDiag = false; + switch (kind) { + case 0 /* Find */: + if (!project) return; + break; + case 1 /* Create */: + project ?? (project = this.createConfiguredProject(configFileName, reason)); + sentConfigFileDiag = !delayLoad && updateConfiguredProject(project, triggerFile); + break; + case 2 /* Reload */: + project ?? (project = this.createConfiguredProject(configFileName, reloadReason(reason))); + sentConfigFileDiag = !delayReloadedConfiguredProjects && this.reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects); + if (delayReloadedConfiguredProjects && !delayReloadedConfiguredProjects.has(project) && !reloadedProjects.has(project)) { + project.pendingUpdateLevel = 2 /* Full */; + project.pendingUpdateReason = reloadReason(reason); + delayReloadedConfiguredProjects.add(project); + } + break; + default: + Debug.assertNever(kind); + } + return { project, sentConfigFileDiag }; + } + /** + * Finds the default configured project for given info + * For any tsconfig found, it looks into that project, if not then all its references, + * The search happens for all tsconfigs till projectRootPath + */ + tryFindDefaultConfiguredProjectForOpenScriptInfo(info, kind, allowDeferredClosed, reloadedProjects) { + const configFileName = this.getConfigFileNameForFile(info, kind === 0 /* Find */); + if (!configFileName) return; + const result = this.findCreateOrReloadConfiguredProject( + configFileName, + kind, + fileOpenReason(info), + allowDeferredClosed, + info.fileName, + reloadedProjects + ); + if (!result) return; + const seenProjects = /* @__PURE__ */ new Set(); + const sentConfigDiag = new Set(result.sentConfigFileDiag ? [result.project] : void 0); + let defaultProject; + let possiblyDefault; + tryFindDefaultConfiguredProject(result.project); + return { + defaultProject: defaultProject ?? possiblyDefault, + sentConfigDiag, + seenProjects + }; + function tryFindDefaultConfiguredProject(project) { + return isDefaultProject(project) ? defaultProject : tryFindDefaultConfiguredProjectFromReferences(project); + } + function isDefaultProject(project) { + if (!tryAddToSet(seenProjects, project)) return; + const projectWithInfo = project.containsScriptInfo(info); + if (projectWithInfo && !project.isSourceOfProjectReferenceRedirect(info.path)) return defaultProject = project; + possiblyDefault ?? (possiblyDefault = projectWithInfo ? project : void 0); + } + function tryFindDefaultConfiguredProjectFromReferences(project) { + return forEachResolvedProjectReferenceProject( + project, + info.path, + (child, sentConfigFileDiag) => { + if (sentConfigFileDiag) sentConfigDiag.add(child); + return isDefaultProject(child); + }, + kind, + `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`, + allowDeferredClosed, + info.fileName, + reloadedProjects + ); + } + } + tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(info, kind, reloadedProjects, delayReloadedConfiguredProjects) { + const allowDeferredClosed = kind === 0 /* Find */; + const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( + info, + kind, + allowDeferredClosed, + reloadedProjects + ); + if (!result) return; + const { defaultProject, seenProjects } = result; + if (defaultProject) { + forEachAncestorProject( + info, + defaultProject, + (ancestor) => { + seenProjects.add(ancestor); + }, + kind, + `Creating project possibly referencing default composite project ${defaultProject.getProjectName()} of open file ${info.fileName}`, + allowDeferredClosed, + reloadedProjects, + delayReloadedConfiguredProjects + ); } + return result; } /** @internal */ loadAncestorProjectTree(forProjects) { @@ -187143,27 +187435,36 @@ Dynamic files must always be opened with service's current directory or service } ensureProjectChildren(project, forProjects, seenProjects) { var _a; - if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) - return; - if (project.getCompilerOptions().disableReferencedProjectLoad) - return; + if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) return; + if (project.getCompilerOptions().disableReferencedProjectLoad) return; const children = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); - if (!children) - return; + if (!children) return; for (const child of children) { - if (!child) - continue; + if (!child) continue; const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0); - if (!referencedProject) - continue; + if (!referencedProject) continue; const configFileName = toNormalizedPath(child.sourceFile.fileName); - const childProject = project.projectService.findConfiguredProjectByProjectName(configFileName) || project.projectService.createAndLoadConfiguredProject(configFileName, `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}`); + const childProject = this.findConfiguredProjectByProjectName(configFileName) ?? this.createConfiguredProject( + configFileName, + `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}` + ); updateProjectIfDirty(childProject); this.ensureProjectChildren(childProject, forProjects, seenProjects); } } - cleanupAfterOpeningFile(toRetainConfigProjects) { - this.removeOrphanConfiguredProjects(toRetainConfigProjects); + cleanupConfiguredProjects(toRetainConfiguredProjects, externalProjectsRetainingConfiguredProjects, openFilesWithRetainedConfiguredProject) { + this.getOrphanConfiguredProjects( + toRetainConfiguredProjects, + openFilesWithRetainedConfiguredProject, + externalProjectsRetainingConfiguredProjects + ).forEach((project) => this.removeProject(project)); + } + cleanupProjectsAndScriptInfos(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) { + this.cleanupConfiguredProjects( + toRetainConfiguredProjects, + externalProjectsRetainingConfiguredProjects, + openFilesWithRetainedConfiguredProject + ); for (const inferredProject of this.inferredProjects.slice()) { if (inferredProject.isOrphan()) { this.removeProject(inferredProject); @@ -187174,17 +187475,18 @@ Dynamic files must always be opened with service's current directory or service openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info); - this.cleanupAfterOpeningFile(retainProjects); + this.cleanupProjectsAndScriptInfos( + retainProjects, + /* @__PURE__ */ new Set([info.path]), + /*externalProjectsRetainingConfiguredProjects*/ + void 0 + ); this.telemetryOnOpenFile(info); this.printProjects(); return result; } - removeOrphanConfiguredProjects(toRetainConfiguredProjects) { - const orphanConfiguredProjects = this.getOrphanConfiguredProjects(toRetainConfiguredProjects); - orphanConfiguredProjects.forEach((project) => this.removeProject(project)); - } /** @internal */ - getOrphanConfiguredProjects(toRetainConfiguredProjects) { + getOrphanConfiguredProjects(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) { const toRemoveConfiguredProjects = new Set(this.configuredProjects.values()); const markOriginalProjectsAsUsed = (project) => { if (project.originalConfiguredProjects && (isConfiguredProject(project) || !project.isOrphan())) { @@ -187196,43 +187498,53 @@ Dynamic files must always be opened with service's current directory or service ); } }; - if (toRetainConfiguredProjects) { - if (isArray(toRetainConfiguredProjects)) { - toRetainConfiguredProjects.forEach(retainConfiguredProject); - } else { - retainConfiguredProject(toRetainConfiguredProjects); - } - } + toRetainConfiguredProjects == null ? void 0 : toRetainConfiguredProjects.forEach(retainConfiguredProject); this.inferredProjects.forEach(markOriginalProjectsAsUsed); this.externalProjects.forEach(markOriginalProjectsAsUsed); + this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => { + if (!(externalProjectsRetainingConfiguredProjects == null ? void 0 : externalProjectsRetainingConfiguredProjects.has(externalProjectName))) { + projects.forEach(retainConfiguredProject); + } + }); + this.openFiles.forEach((_projectRootPath, path) => { + if (openFilesWithRetainedConfiguredProject == null ? void 0 : openFilesWithRetainedConfiguredProject.has(path)) return; + const info = this.getScriptInfoForPath(path); + if (find(info.containingProjects, isExternalProject)) return; + const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( + info, + 0 /* Find */ + ); + if (result == null ? void 0 : result.defaultProject) { + result == null ? void 0 : result.seenProjects.forEach(retainConfiguredProject); + } + }); this.configuredProjects.forEach((project) => { - if (!toRemoveConfiguredProjects.has(project)) - return; - if (project.hasOpenRef()) { - retainConfiguredProject(project); - } else if (forEachReferencedProject(project, (ref) => isRetained(ref))) { - retainConfiguredProject(project); + if (toRemoveConfiguredProjects.has(project)) { + if (isPendingUpdate(project) || forEachReferencedProject(project, isRetained)) { + retainConfiguredProject(project); + } } }); return toRemoveConfiguredProjects; function isRetained(project) { - return !toRemoveConfiguredProjects.has(project) || project.hasOpenRef(); + return !toRemoveConfiguredProjects.has(project) || isPendingUpdate(project); + } + function isPendingUpdate(project) { + var _a, _b; + return (project.deferredClose || project.projectService.hasPendingProjectUpdate(project)) && !!((_b = (_a = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)) == null ? void 0 : _a.openFilesImpactedByConfigFile) == null ? void 0 : _b.size); } function retainConfiguredProject(project) { - if (toRemoveConfiguredProjects.delete(project)) { - markOriginalProjectsAsUsed(project); - forEachReferencedProject(project, retainConfiguredProject); - } + if (!toRemoveConfiguredProjects.delete(project)) return; + markOriginalProjectsAsUsed(project); + forEachReferencedProject(project, retainConfiguredProject); } } removeOrphanScriptInfos() { const toRemoveScriptInfos = new Map(this.filenameToScriptInfo); this.filenameToScriptInfo.forEach((info) => { - if (info.deferredDelete) - return; + if (info.deferredDelete) return; if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) { - if (!info.sourceMapFilePath) - return; + if (!info.sourceMapFilePath) return; let sourceInfos; if (isString(info.sourceMapFilePath)) { const sourceMapInfo = this.filenameToScriptInfo.get(info.sourceMapFilePath); @@ -187240,8 +187552,7 @@ Dynamic files must always be opened with service's current directory or service } else { sourceInfos = info.sourceMapFilePath.sourceInfos; } - if (!sourceInfos) - return; + if (!sourceInfos) return; if (!forEachKey(sourceInfos, (path) => { const info2 = this.getScriptInfoForPath(path); return !!info2 && (info2.isScriptOpen() || !info2.isOrphan()); @@ -187340,14 +187651,20 @@ Dynamic files must always be opened with service's current directory or service } } let retainProjects; - if (openScriptInfos) { - retainProjects = flatMap(openScriptInfos, (info) => this.assignProjectToOpenedScriptInfo(info).retainProjects); - } + openScriptInfos == null ? void 0 : openScriptInfos.forEach((info) => { + var _a; + return (_a = this.assignProjectToOpenedScriptInfo(info).retainProjects) == null ? void 0 : _a.forEach((p) => (retainProjects ?? (retainProjects = /* @__PURE__ */ new Set())).add(p)); + }); if (assignOrphanScriptInfosToInferredProject) { this.assignOrphanScriptInfosToInferredProject(); } if (openScriptInfos) { - this.cleanupAfterOpeningFile(retainProjects); + this.cleanupProjectsAndScriptInfos( + retainProjects, + new Set(openScriptInfos.map((info) => info.path)), + /*externalProjectsRetainingConfiguredProjects*/ + void 0 + ); openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info)); this.printProjects(); } else if (length(closedFiles)) { @@ -187360,21 +187677,11 @@ Dynamic files must always be opened with service's current directory or service scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); } } - closeConfiguredProjectReferencedFromExternalProject(configuredProjects) { - configuredProjects == null ? void 0 : configuredProjects.forEach((configuredProject) => { - if (!configuredProject.isClosed()) { - configuredProject.deleteExternalProjectReference(); - if (!configuredProject.hasOpenRef()) - this.removeProject(configuredProject); - } - }); - } // eslint-disable-line @typescript-eslint/unified-signatures - closeExternalProject(uncheckedFileName, print) { + closeExternalProject(uncheckedFileName, cleanupAfter) { const fileName = toNormalizedPath(uncheckedFileName); - const configuredProjects = this.externalProjectToConfiguredProjectMap.get(fileName); - if (configuredProjects) { - this.closeConfiguredProjectReferencedFromExternalProject(configuredProjects); + const projects = this.externalProjectToConfiguredProjectMap.get(fileName); + if (projects) { this.externalProjectToConfiguredProjectMap.delete(fileName); } else { const externalProject = this.findExternalProjectByProjectName(uncheckedFileName); @@ -187382,29 +187689,28 @@ Dynamic files must always be opened with service's current directory or service this.removeProject(externalProject); } } - if (print) + if (cleanupAfter) { + this.cleanupConfiguredProjects(); this.printProjects(); + } } openExternalProjects(projects) { - const projectsToClose = arrayToMap(this.externalProjects, (p) => p.getProjectName(), (_) => true); - forEachKey(this.externalProjectToConfiguredProjectMap, (externalProjectName) => { - projectsToClose.set(externalProjectName, true); - }); + const projectsToClose = new Set(this.externalProjects.map((p) => p.getProjectName())); + this.externalProjectToConfiguredProjectMap.forEach((_, externalProjectName) => projectsToClose.add(externalProjectName)); for (const externalProject of projects) { this.openExternalProject( externalProject, - /*print*/ + /*cleanupAfter*/ false ); projectsToClose.delete(externalProject.projectFileName); } - forEachKey(projectsToClose, (externalProjectName) => { - this.closeExternalProject( - externalProjectName, - /*print*/ - false - ); - }); + projectsToClose.forEach((externalProjectName) => this.closeExternalProject( + externalProjectName, + /*cleanupAfter*/ + false + )); + this.cleanupConfiguredProjects(); this.printProjects(); } static escapeFilenameForRegex(filename) { @@ -187509,9 +187815,8 @@ Dynamic files must always be opened with service's current directory or service } } // eslint-disable-line @typescript-eslint/unified-signatures - openExternalProject(proj, print) { + openExternalProject(proj, cleanupAfter) { const existingExternalProject = this.findExternalProjectByProjectName(proj.projectFileName); - const existingConfiguredProjects = this.externalProjectToConfiguredProjectMap.get(proj.projectFileName); let configuredProjects; let rootFiles = []; for (const file of proj.rootFiles) { @@ -187520,13 +187825,11 @@ Dynamic files must always be opened with service's current directory or service if (this.serverMode === 0 /* Semantic */ && this.host.fileExists(normalized)) { let project = this.findConfiguredProjectByProjectName(normalized); if (!project) { - project = this.getHostPreferences().lazyConfiguredProjectsFromExternalProject ? this.createConfiguredProjectWithDelayLoad(normalized, `Creating configured project in external project: ${proj.projectFileName}`) : this.createLoadAndUpdateConfiguredProject(normalized, `Creating configured project in external project: ${proj.projectFileName}`); - } - if (!(existingConfiguredProjects == null ? void 0 : existingConfiguredProjects.has(project))) { - project.addExternalProjectReference(); + project = this.createConfiguredProject(normalized, `Creating configured project in external project: ${proj.projectFileName}`); + if (!this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) project.updateGraph(); } (configuredProjects ?? (configuredProjects = /* @__PURE__ */ new Set())).add(project); - existingConfiguredProjects == null ? void 0 : existingConfiguredProjects.delete(project); + Debug.assert(!project.isClosed()); } } else { rootFiles.push(file); @@ -187534,8 +187837,7 @@ Dynamic files must always be opened with service's current directory or service } if (configuredProjects) { this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, configuredProjects); - if (existingExternalProject) - this.removeProject(existingExternalProject); + if (existingExternalProject) this.removeProject(existingExternalProject); } else { this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); const typeAcquisition = proj.typeAcquisition || {}; @@ -187565,9 +187867,13 @@ Dynamic files must always be opened with service's current directory or service project.updateGraph(); } } - this.closeConfiguredProjectReferencedFromExternalProject(existingConfiguredProjects); - if (print) + if (cleanupAfter) { + this.cleanupConfiguredProjects( + configuredProjects, + new Set(proj.projectFileName) + ); this.printProjects(); + } } hasDeferredExtension() { for (const extension of this.hostConfiguration.extraFileExtensions) { @@ -187600,8 +187906,7 @@ Dynamic files must always be opened with service's current directory or service ); this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); let promises = this.pendingPluginEnablements.get(project); - if (!promises) - this.pendingPluginEnablements.set(project, promises = []); + if (!promises) this.pendingPluginEnablements.set(project, promises = []); promises.push(importPromise); return; } @@ -187690,8 +187995,7 @@ Dynamic files must always be opened with service's current directory or service this.delayUpdateProjectGraph(project); })); this.currentPluginEnablementPromise = void 0; - if (sendProjectsUpdatedInBackgroundEvent) - this.sendProjectsUpdatedInBackgroundEvent(); + if (sendProjectsUpdatedInBackgroundEvent) this.sendProjectsUpdatedInBackgroundEvent(); } configurePlugin(args) { this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); @@ -187712,8 +188016,7 @@ Dynamic files must always be opened with service's current directory or service const packageJsonFileName = combinePaths(directory, "package.json"); this.watchPackageJsonFile(packageJsonFileName, this.toPath(packageJsonFileName), project); const info = packageJsonCache.getInDirectory(directory); - if (info) - result.push(info); + if (info) result.push(info); } if (rootPath && rootPath === directory) { return true; @@ -187764,8 +188067,7 @@ Dynamic files must always be opened with service's current directory or service projects: /* @__PURE__ */ new Set(), close: () => { var _a; - if (result.projects.size || !watcher) - return; + if (result.projects.size || !watcher) return; watcher.close(); watcher = void 0; (_a = this.packageJsonFilesMap) == null ? void 0 : _a.delete(path); @@ -187838,12 +188140,12 @@ function createModuleSpecifierCache(host) { let currentKey; const result = { get(fromFileName, toFileName2, preferences, options) { - if (!cache || currentKey !== key(fromFileName, preferences, options)) - return void 0; + if (!cache || currentKey !== key(fromFileName, preferences, options)) return void 0; return cache.get(toFileName2); }, - set(fromFileName, toFileName2, preferences, options, modulePaths, moduleSpecifiers) { + set(fromFileName, toFileName2, preferences, options, kind, modulePaths, moduleSpecifiers) { ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo( + kind, modulePaths, moduleSpecifiers, /*isBlockedByPackageJsonDependencies*/ @@ -187871,6 +188173,8 @@ function createModuleSpecifierCache(host) { info.modulePaths = modulePaths; } else { cache2.set(toFileName2, createInfo( + /*kind*/ + void 0, modulePaths, /*moduleSpecifiers*/ void 0, @@ -187886,6 +188190,8 @@ function createModuleSpecifierCache(host) { info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies; } else { cache2.set(toFileName2, createInfo( + /*kind*/ + void 0, /*modulePaths*/ void 0, /*moduleSpecifiers*/ @@ -187919,8 +188225,8 @@ function createModuleSpecifierCache(host) { function key(fromFileName, preferences, options) { return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`; } - function createInfo(modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) { - return { modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; + function createInfo(kind, modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies) { + return { kind, modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; } } @@ -188247,20 +188553,17 @@ function getReferencesWorker(projects, defaultProject, initialLocation, useCaseS while (true) { let progress = false; perProjectResults.forEach((referencedSymbols, project) => { - if (updatedProjects.has(project)) - return; + if (updatedProjects.has(project)) return; const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans); if (updated) { updatedProjects.add(project); progress = true; } }); - if (!progress) - break; + if (!progress) break; } perProjectResults.forEach((referencedSymbols, project) => { - if (updatedProjects.has(project)) - return; + if (updatedProjects.has(project)) return; for (const referencedSymbol of referencedSymbols) { for (const ref of referencedSymbol.references) { ref.isDefinition = false; @@ -188328,13 +188631,10 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo onCancellation: while (!queue.isEmpty()) { while (!queue.isEmpty()) { - if (cancellationToken.isCancellationRequested()) - break onCancellation; + if (cancellationToken.isCancellationRequested()) break onCancellation; const { project, location } = queue.dequeue(); - if (resultsMap.has(project)) - continue; - if (isLocationProjectReferenceRedirect(project, location)) - continue; + if (resultsMap.has(project)) continue; + if (isLocationProjectReferenceRedirect(project, location)) continue; updateProjectIfDirty(project); if (!project.containsFile(toNormalizedPath(location.fileName))) { continue; @@ -188346,10 +188646,8 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo if (defaultDefinition) { projectService.loadAncestorProjectTree(searchedProjectKeys); projectService.forEachEnabledProject((project) => { - if (cancellationToken.isCancellationRequested()) - return; - if (resultsMap.has(project)) - return; + if (cancellationToken.isCancellationRequested()) return; + if (resultsMap.has(project)) return; const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); if (location) { queue.enqueue({ project, location }); @@ -188363,13 +188661,11 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo return resultsMap; function searchPosition(project, location) { const projectResults = getResultsForPosition(project, location); - if (!projectResults) - return void 0; + if (!projectResults) return void 0; for (const result of projectResults) { forPositionInResult(result, (position) => { const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); - if (!originalLocation) - return; + if (!originalLocation) return; const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); for (const project2 of originalScriptInfo.containingProjects) { if (!project2.isOrphan() && !resultsMap.has(project2)) { @@ -188396,17 +188692,14 @@ function mapDefinitionInProject(definition, project, getGeneratedDefinition, get return definition; } const generatedDefinition = getGeneratedDefinition(); - if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) - return generatedDefinition; + if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) return generatedDefinition; const sourceDefinition = getSourceDefinition(); return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : void 0; } function isLocationProjectReferenceRedirect(project, location) { - if (!location) - return false; + if (!location) return false; const program = project.getLanguageService().getProgram(); - if (!program) - return false; + if (!program) return false; const sourceFile = program.getSourceFile(location.fileName); return !!sourceFile && sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); } @@ -188456,7 +188749,8 @@ var invalidPartialSemanticModeCommands = [ "getEditsForFileRename-full" /* GetEditsForFileRenameFull */, "prepareCallHierarchy" /* PrepareCallHierarchy */, "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, - "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */ + "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */, + "getPasteEdits" /* GetPasteEdits */ ]; var invalidSyntacticModeCommands = [ ...invalidPartialSemanticModeCommands, @@ -188498,7 +188792,7 @@ var Session3 = class _Session { ["openExternalProject" /* OpenExternalProject */]: (request) => { this.projectService.openExternalProject( request.arguments, - /*print*/ + /*cleanupAfter*/ true ); return this.requiredResponse( @@ -188516,7 +188810,7 @@ var Session3 = class _Session { ["closeExternalProject" /* CloseExternalProject */]: (request) => { this.projectService.closeExternalProject( request.arguments.projectFileName, - /*print*/ + /*cleanupAfter*/ true ); return this.requiredResponse( @@ -189004,6 +189298,9 @@ var Session3 = class _Session { ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); }, + ["getPasteEdits" /* GetPasteEdits */]: (request) => { + return this.requiredResponse(this.getPasteEdits(request.arguments)); + }, ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { return this.requiredResponse(this.getEditsForRefactor( request.arguments, @@ -189132,6 +189429,9 @@ var Session3 = class _Session { }, ["provideInlayHints" /* ProvideInlayHints */]: (request) => { return this.requiredResponse(this.provideInlayHints(request.arguments)); + }, + ["mapCode" /* MapCode */]: (request) => { + return this.requiredResponse(this.mapCode(request.arguments)); } })); this.host = opts.host; @@ -189388,8 +189688,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } else { res.body = info; } - if (metadata) - res.metadata = metadata; + if (metadata) res.metadata = metadata; } else { Debug.assert(info === void 0); } @@ -189680,8 +189979,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient); for (const candidate of some(ambientCandidates) ? ambientCandidates : getAmbientCandidatesByClimbingAccessChain()) { const fileNameToSearch = findImplementationFileFromDtsFileName(candidate.fileName, file, noDtsProject); - if (!fileNameToSearch) - continue; + if (!fileNameToSearch) continue; const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( fileNameToSearch, noDtsProject.currentDirectory, @@ -189689,8 +189987,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter /*deferredDeleteOk*/ false ); - if (!info) - continue; + if (!info) continue; if (!noDtsProject.containsScriptInfo(info)) { noDtsProject.addRoot(info); noDtsProject.updateGraph(); @@ -189714,8 +190011,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache(); const compilerOptions = project.getCompilationSettings(); const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory + "/package.json", project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); - if (!packageJson) - return void 0; + if (!packageJson) return void 0; const entrypoints = getEntrypointsFromPackageJsonInfo( packageJson, { moduleResolution: 2 /* Node10 */ }, @@ -189745,8 +190041,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) { return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => { var _a2; - if (nameInChain === initialNode) - return void 0; + if (nameInChain === initialNode) return void 0; const candidates = (_a2 = ls.getDefinitionAtPosition( file, nameInChain.getStart(), @@ -189774,8 +190069,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); const symbol = program.getTypeChecker().getSymbolAtLocation(initialNode); const importSpecifier = symbol && getDeclarationOfKind(symbol, 276 /* ImportSpecifier */); - if (!importSpecifier) - return void 0; + if (!importSpecifier) return void 0; const nameToSearch = ((_a2 = importSpecifier.propertyName) == null ? void 0 : _a2.text) || importSpecifier.name.text; return searchForDeclaration(nameToSearch, fileToSearch, noDtsProgram); } @@ -189952,18 +190246,15 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const position = this.getPositionInFile(args, file); const linkedEditInfo = languageService.getLinkedEditingRangeAtPosition(file, position); const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - if (scriptInfo === void 0 || linkedEditInfo === void 0) - return void 0; + if (scriptInfo === void 0 || linkedEditInfo === void 0) return void 0; return convertLinkedEditInfoToRanges(linkedEditInfo, scriptInfo); } getDocumentHighlights(args, simplifiedResult) { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); - if (!documentHighlights) - return emptyArray2; - if (!simplifiedResult) - return documentHighlights; + if (!documentHighlights) return emptyArray2; + if (!simplifiedResult) return documentHighlights; return documentHighlights.map(({ fileName, highlightSpans }) => { const scriptInfo = project.getScriptInfo(fileName); return { @@ -190003,6 +190294,25 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter }; }); } + mapCode(args) { + var _a; + const formatOptions = this.getHostFormatOptions(); + const preferences = this.getHostPreferences(); + const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); + const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); + const focusLocations = (_a = args.mapping.focusLocations) == null ? void 0 : _a.map((spans) => { + return spans.map((loc) => { + const start = scriptInfo.lineOffsetToPosition(loc.start.line, loc.start.offset); + const end = scriptInfo.lineOffsetToPosition(loc.end.line, loc.end.offset); + return { + start, + length: end - start + }; + }); + }); + const changes = languageService.mapCode(file, args.mapping.contents, focusLocations, formatOptions, preferences); + return this.mapTextChangesToCodeEdits(changes); + } setCompilerOptionsForInferredProjects(args) { this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); } @@ -190046,8 +190356,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } else { const scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); if (!scriptInfo) { - if (ignoreNoProjectError) - return emptyArray2; + if (ignoreNoProjectError) return emptyArray2; this.projectService.logErrorForScriptInfoNotFound(args.file); return Errors.ThrowNoProject(); } else if (!getScriptInfoEnsuringProjectsUptoDate) { @@ -190086,8 +190395,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter defaultProject.getLanguageService().getRenameInfo(file, position, preferences), Debug.checkDefined(this.projectService.getScriptInfo(file)) ); - if (!renameInfo.canRename) - return simplifiedResult ? { info: renameInfo, locs: [] } : []; + if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : []; const locations = getRenameLocationsWorker( projects, defaultProject, @@ -190097,8 +190405,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter preferences, this.host.useCaseSensitiveFileNames ); - if (!simplifiedResult) - return locations; + if (!simplifiedResult) return locations; return { info: renameInfo, locs: this.toSpanGroups(locations) }; } mapRenameInfo(info, scriptInfo) { @@ -190115,8 +190422,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const map2 = /* @__PURE__ */ new Map(); for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { let group2 = map2.get(fileName); - if (!group2) - map2.set(fileName, group2 = { file: fileName, locs: [] }); + if (!group2) map2.set(fileName, group2 = { file: fileName, locs: [] }); const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName)); group2.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText }); } @@ -190133,8 +190439,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.host.useCaseSensitiveFileNames, this.logger ); - if (!simplifiedResult) - return references; + if (!simplifiedResult) return references; const preferences = this.getPreferences(file); const defaultProject = this.getDefaultProject(args); const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); @@ -190159,8 +190464,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter /*path*/ void 0, (project) => { - if (project.getCancellationToken().isCancellationRequested()) - return; + if (project.getCancellationToken().isCancellationRequested()) return; const projectOutputs = project.getLanguageService().getFileReferences(fileName); if (projectOutputs) { for (const referenceEntry of projectOutputs) { @@ -190172,8 +190476,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } } ); - if (!simplifiedResult) - return references; + if (!simplifiedResult) return references; const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); return { refs, @@ -190386,10 +190689,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter }, project.projectService.getFormatCodeOptions(file) ); - if (completions === void 0) - return void 0; - if (kind === "completions-full" /* CompletionsFull */) - return completions; + if (completions === void 0) return void 0; + if (kind === "completions-full" /* CompletionsFull */) return completions; const prefix = args.prefix || ""; const entries = mapDefined(completions.entries, (entry) => { if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { @@ -190433,8 +190734,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } }); if (kind === "completions" /* Completions */) { - if (completions.metadata) - entries.metadata = completions.metadata; + if (completions.metadata) entries.metadata = completions.metadata; return entries; } const res = { @@ -190733,15 +191033,13 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } } getSupportedCodeFixes(args) { - if (!args) - return getSupportedCodeFixes(); + if (!args) return getSupportedCodeFixes(); if (args.file) { const { file, project: project2 } = this.getFileAndProject(args); return project2.getLanguageService().getSupportedCodeFixes(file); } const project = this.getProject(args.projectFileName); - if (!project) - Errors.ThrowNoProject(); + if (!project) Errors.ThrowNoProject(); return project.getLanguageService().getSupportedCodeFixes(); } isLocation(locationOrSpan) { @@ -190808,6 +191106,21 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const scriptInfo = project.getScriptInfoForNormalizedPath(file); return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } + getPasteEdits(args) { + const { file, project } = this.getFileAndProject(args); + const copiedFrom = args.copiedFrom ? { file: args.copiedFrom.file, range: args.copiedFrom.spans.map((copies) => this.getRange({ file: args.copiedFrom.file, startLine: copies.start.line, startOffset: copies.start.offset, endLine: copies.end.line, endOffset: copies.end.offset }, project.getScriptInfoForNormalizedPath(toNormalizedPath(args.copiedFrom.file)))) } : void 0; + const result = project.getLanguageService().getPasteEdits( + { + targetFile: file, + pastedText: args.pastedText, + pasteLocations: args.pasteLocations.map((paste) => this.getRange({ file, startLine: paste.start.line, startOffset: paste.start.offset, endLine: paste.end.line, endOffset: paste.end.offset }, project.getScriptInfoForNormalizedPath(file))), + copiedFrom, + preferences: this.getPreferences(file) + }, + this.getFormatOptions(file) + ); + return result && this.mapPasteEditsAction(result); + } organizeImports(args, simplifiedResult) { Debug.assert(args.scope.type === "file"); const { file, project } = this.getFileAndProject(args.scope.args); @@ -190874,10 +191187,10 @@ ${e.message}`; } return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions; } - getCombinedCodeFix({ scope, fixId: fixId53 }, simplifiedResult) { + getCombinedCodeFix({ scope, fixId: fixId55 }, simplifiedResult) { Debug.assert(scope.type === "file"); const { file, project } = this.getFileAndProject(scope.args); - const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId53, this.getFormatOptions(file), this.getPreferences(file)); + const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId55, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; } else { @@ -190916,8 +191229,11 @@ ${e.message}`; mapCodeAction({ description: description3, changes, commands }) { return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; } - mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId53, fixAllDescription }) { - return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId53, fixAllDescription }; + mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId55, fixAllDescription }) { + return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId55, fixAllDescription }; + } + mapPasteEditsAction({ edits, fixId: fixId55 }) { + return { edits: this.mapTextChangesToCodeEdits(edits), fixId: fixId55 }; } mapTextChangesToCodeEdits(textChanges2) { return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); @@ -191305,8 +191621,7 @@ function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) { }; } ); - if (!linkedEdit.wordPattern) - return { ranges }; + if (!linkedEdit.wordPattern) return { ranges }; return { ranges, wordPattern: linkedEdit.wordPattern }; } function locationFromLineAndCharacter(lc) { @@ -191467,8 +191782,7 @@ var EditWalker = class { function fresh(node) { if (node.isLeaf()) { return new LineLeaf(""); - } else - return new LineNode(); + } else return new LineNode(); } switch (nodeType) { case 0 /* PreStart */: @@ -191818,8 +192132,7 @@ var LineNode = class _LineNode { this.children = children; this.totalChars = 0; this.totalLines = 0; - if (children.length) - this.updateCounts(); + if (children.length) this.updateCounts(); } isLeaf() { return false; @@ -192244,6 +192557,7 @@ __export(ts_server_exports4, { CommandNames: () => CommandNames, ConfigFileDiagEvent: () => ConfigFileDiagEvent, ConfiguredProject: () => ConfiguredProject2, + ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind, CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, CreateFileWatcherEvent: () => CreateFileWatcherEvent, Errors: () => Errors, @@ -192251,7 +192565,7 @@ __export(ts_server_exports4, { EventEndInstallTypes: () => EventEndInstallTypes, EventInitializationFailed: () => EventInitializationFailed, EventTypesRegistry: () => EventTypesRegistry, - ExternalProject: () => ExternalProject2, + ExternalProject: () => ExternalProject, GcTimer: () => GcTimer, InferredProject: () => InferredProject2, LargeFileReferencedEvent: () => LargeFileReferencedEvent, @@ -192267,7 +192581,6 @@ __export(ts_server_exports4, { ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectReferenceProjectLoadKind: () => ProjectReferenceProjectLoadKind, ProjectService: () => ProjectService3, ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, ScriptInfo: () => ScriptInfo, @@ -192319,7 +192632,6 @@ __export(ts_server_exports4, { nowString: () => nowString, nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, - projectContainsInfoDirectly: () => projectContainsInfoDirectly, protocol: () => ts_server_protocol_exports, removeSorted: () => removeSorted, stringifyIndented: () => stringifyIndented, @@ -192381,7 +192693,6 @@ if (typeof console !== "undefined") { EmitHint, EmitOnly, EndOfLineState, - EnumKind, ExitStatus, ExportKind, Extension, @@ -192412,6 +192723,7 @@ if (typeof console !== "undefined") { InlayHints, InternalEmitFlags, InternalSymbolName, + IntersectionFlags, InvalidatedProjectKind, JSDocParsingMode, JsDoc, @@ -192425,6 +192737,7 @@ if (typeof console !== "undefined") { LexicalEnvironmentFlags, ListFormat, LogLevel, + MapCode, MemberOverrideStatus, ModifierFlags, ModuleDetectionKind, @@ -192572,6 +192885,7 @@ if (typeof console !== "undefined") { canHaveModifiers, canHaveModuleSpecifier, canHaveSymbol, + canIncludeBindAndCheckDiagnsotics, canJsonReportNoInputFiles, canProduceDiagnostics, canUsePropertyAccess, @@ -192615,6 +192929,7 @@ if (typeof console !== "undefined") { collectExternalModuleInfo, combine, combinePaths, + commandLineOptionOfCustomType, commentPragmas, commonOptionsWithBuild, commonPackageFolders, @@ -192824,6 +193139,7 @@ if (typeof console !== "undefined") { defaultMaximumTruncationLength, diagnosticCategoryName, diagnosticToString, + diagnosticsEqualityComparer, directoryProbablyExists, directorySeparator, displayPart, @@ -192843,6 +193159,7 @@ if (typeof console !== "undefined") { emitNewLineBeforeLeadingCommentOfPosition, emitNewLineBeforeLeadingComments, emitNewLineBeforeLeadingCommentsOfPosition, + emitResolverSkipsTypeChecking, emitSkippedWithNoDiagnostics, emptyArray, emptyFileSystemEntries, @@ -192942,6 +193259,7 @@ if (typeof console !== "undefined") { forEachKey, forEachLeadingCommentRange, forEachNameInAccessChainWalkingLeft, + forEachNameOfDefaultExport, forEachPropertyAssignment, forEachResolvedProjectReference, forEachReturnStatement, @@ -192997,6 +193315,7 @@ if (typeof console !== "undefined") { getBuildOrderFromAnyBuildOrder, getBuilderCreationParameters, getBuilderFileEmit, + getCanonicalDiagnostic, getCheckFlags, getClassExtendsHeritageElement, getClassLikeDeclarationOfSymbol, @@ -193037,11 +193356,11 @@ if (typeof console !== "undefined") { getDeclaredExpandoInitializer, getDecorators, getDefaultCompilerOptions, - getDefaultExportInfoWorker, getDefaultFormatCodeSettings, getDefaultLibFileName, getDefaultLibFilePath, getDefaultLikeExportInfo, + getDefaultLikeExportNameFromDeclaration, getDefaultResolutionModeForFileWorker, getDiagnosticText, getDiagnosticsWithinSpan, @@ -193376,6 +193695,7 @@ if (typeof console !== "undefined") { getSwitchedType, getSymbolId, getSymbolNameForPrivateIdentifier, + getSymbolParentOrFail, getSymbolTarget, getSyntacticClassifications, getSyntacticModifierFlags, @@ -194207,7 +194527,6 @@ if (typeof console !== "undefined") { loadWithModeAwareCache, makeIdentifierFromModuleName, makeImport, - makeImportIfNecessary, makeStringLiteral, mangleScopedPackageName, map, @@ -194241,7 +194560,9 @@ if (typeof console !== "undefined") { moduleResolutionOptionDeclarations, moduleResolutionSupportsPackageJsonExportsAndImports, moduleResolutionUsesNodeModules, + moduleSpecifierToValidIdentifier, moduleSpecifiers, + moduleSymbolToValidIdentifier, moveEmitHelpers, moveRangeEnd, moveRangePastDecorators, @@ -194321,6 +194642,7 @@ if (typeof console !== "undefined") { parsePackageName, parsePseudoBigInt, parseValidBigInt, + pasteEdits, patchWriteFileEnsuringDirectory, pathContainsNodeModules, pathIsAbsolute, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index fd8844b3212dd..3b2d0e0eeb0b1 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -65,8 +65,7 @@ var FileLog = class { return typeof this.logFile === "string"; }; this.writeLine = (text) => { - if (typeof this.logFile !== "string") - return; + if (typeof this.logFile !== "string") return; try { fs.appendFileSync(this.logFile, `[${typescript_exports.server.nowString()}] ${text}${typescript_exports.sys.newLine}`); } catch (e) {